【问题标题】:How to get year and month separately from this string in sql server?如何在sql server中从这个字符串中分别获取年份和月份?
【发布时间】:2011-01-04 02:21:15
【问题描述】:

我有这个字符串格式mm/yyyy-

01/2010

我如何分别获得月份和年份。我想要分别 01 和 2010 年,我可以比较它们吗?

【问题讨论】:

    标签: sql sql-server-2005 date


    【解决方案1】:

    这应该让你了解(假设@Date 代表你的日期字符串):

    DECLARE @SlashPos int;
    SET @SlashPos = CHARINDEX('/', @Date);
    
    Declare @Month varchar(2);
    Declare @Year varchar(4);
    
    SET @Month = SUBSTRING(@Date, 1, @SlashPos - 1);
    Set @Year = SUBSTRING(@Date, @SlashPos + 1, LEN(@Date) - @SlashPos);
    

    此时,@Month@Year 将包含表示月份和年份的字符串。

    【讨论】:

    • 我的荣幸。如果您的月份都是 2 位数长,Leniel 的答案也应该有效,并且更简单。
    【解决方案2】:

    例子:

    declare @d char(7);
    declare @Month varchar(2);
    declare @Year varchar(4);
    
    set @d = '01/2010';
    
    SET @Month = LEFT(@d, 2);
    SET @Year = RIGHT(@d, 4);
    

    【讨论】:

      【解决方案3】:

      查看子字符串和字符索引函数的帮助

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-01-30
        • 2020-04-28
        • 2020-09-18
        • 1970-01-01
        • 1970-01-01
        • 2020-12-19
        • 2013-12-05
        • 2010-09-07
        相关资源
        最近更新 更多