我有这个脚本:
SELECT UserID,
CONVERT(SmallDateTime, cast([1] + '/' + [2] + '/' + [3] as varchar)) as ReleaseDate,
ChannelID
FROM
(
SELECT RU.UserID, U.FieldID, RU.ChannelID, U.AnswerText
FROM dbo.Users U WITH (NOLOCK) INNER JOIN dbo.ResourceUsers RU WITH (NOLOCK)
ON U.UserID = RU.UserID
WHERE (FieldID = 1 -- release day
OR FieldID = 2 -- release month
OR FieldID = 3)
) AS P
PIVOT
(
MAX(AnswerText) FOR FieldID in ([1], [2], [3])
) AS pvt
相同的脚本在服务器上运行完美。在其他服务器上,我收到此错误:
Msg 295,Level 16,State 3,Line 3转换时转换失败 字符串到smalldatetime数据类型。
为什么呢?有什么区别? 这两个服务器上的表具有相同的结构。
答案 0 :(得分:0)
在sql server 2012+中,您可以使用datefromparts
SELECT UserID,
convert(smalldatetime,datefromparts([3],[2],[1])) as ReleaseDate,
ChannelID
FROM ....
在sql server 2012之前,你可以在' yyyyMMdd'中创建一个字符串。格式
SELECT UserID,
convert(smalldatetime,
convert(char(4),[3])
+ right('0'+convert(varchar(3),[2]),2)
+ right('0'+convert(varchar(3),[1]),2)
) as ReleaseDate,
ChannelID
FROM ....