T-SQL:结合当月和月的列

时间:2017-04-04 19:44:53

标签: sql-server tsql isnull

我正在尝试将当前年份以YYYY的形式与月份列中的monthy结合起来。

monthy      monthsname
------------------------
 1          January
 2          February
 3          March
 4          April
 5          May
 6          June
 7          July
 8          August
 9          September
10          October
11          November
12          December

以下是我得到的输出:

monthy  monthsname  month_number
------------------------------------
  5          May            NULL
  6          June           NULL
  8          August         NULL
  9          September      NULL
 10          October        NULL
 11          November       NULL
  1          January        201701
  2          February       201702
  3          March          201703
  4          April          201704
  7          July           201707
 12          December       201712

而不是month_number为null,我试图这样做:

isnull(ss.month_number, cast(convert(varchar(4), DATEPART(year, getdate())) as int) + right('0-- ' + cast(convert(varchar(2), monthy) as int), 2))

我没有得到正确的输出:我希望201705的第一行记录month_number之类的东西

2 个答案:

答案 0 :(得分:1)

根据您的数据类型,您可能希望转换它,但它只是年份* 100加上月份数,以获得您尝试创建的数字的整数表示。

ISNULL(month_number,YEAR(GETDATE())*100+monthy)

答案 1 :(得分:0)

你可以试试这个:

 SELECT 
     CONVERT(VARCHAR(4),DATEPART(YEAR, GETDATE())) +  --year
     (  
        REPLICATE('0', 2 - LEN(CONVERT(VARCHAR(2), monthy)) ) + 
        CONVERT(VARCHAR(2), monthy) --monthy
     )