SQL中的Concat 2 varchars

时间:2016-10-05 14:25:48

标签: sql sql-server tsql

我正在尝试生成一个4个字符年+ 2个字符月的varchar(20)。我想在我的存储过程中使用它作为参数。我无法将2个varchars连接在一起产生这个,任何想法?

SELECT 
    GETDATE() AS CurrentDateTime,
    CONVERT(VARCHAR(20), YEAR(GETDATE())) AS CurrentYear,
    CONVERT(VARCHAR(20), MONTH(GETDATE())) AS CurrentMonth,
    CurrentYear + CurrentMonth AS YearMonth

4 个答案:

答案 0 :(得分:6)

最简单的方法是使用它:

SELECT Format(GetDate(), 'yyyyMM') as YearMonth

函数Format()introduced with Sql Server 2012

答案 1 :(得分:3)

为什么不简单

SELECT GETDATE() AS CurrentDateTime
 , Convert(VARCHAR(20),YEAR(GETDATE())) AS CurrentYear
 , Convert(VARCHAR(20),MONTH(GETDATE())) AS CurrentMonth
 , Convert(varchar(6), GETDATE(), 112) AS YearMonth

答案 2 :(得分:1)

SELECT GETDATE() AS CurrentDateTime
, Convert(VARCHAR(20),YEAR(GETDATE())) +
Convert(VARCHAR(20),MONTH(GETDATE()))

无法从中选择列别名,因此上述情况也可以。

答案 3 :(得分:0)

喜欢这个吗?

SELECT GETDATE() AS CurrentDateTime
 , Convert(VARCHAR(20),YEAR(GETDATE())) AS CurrentYear
 , Convert(VARCHAR(20),MONTH(GETDATE())) AS CurrentMonth
 , Convert(VARCHAR(20),YEAR(GETDATE())) + Convert(VARCHAR(20),MONTH(GETDATE())) AS YearMonth

你也可以

Year(GetDate()) * 100 + Month(GateDate()) AS YearMonth

或使用以下用户提供的构造

Convert(varchar(6), GETDATE(), 112) AS YearMonth