我有一个名为“ tbl_TimeSheet”的表,其中包含一列WorkWeek,数据类型为nvarchar。
[tbl_WorkWeek]
1 | 47-2018
2 | 36-2018
3 | 1-2019
问题是我正在尝试将“-”号之前的第一个数字转换为日期名称月份,并收到一条错误消息,提示“将nvarchar值“ 1-”转换为数据类型int时转换失败”。我可以轻松获得WorkYear,但不能获得月份。我真的不知道该使用“-”符号。
我对数据库和sql真的很陌生。任何帮助,将不胜感激。谢谢!
Current Code:
SELECT WorkWeek,
RIGHT(WorkWeek, 4) AS [WorkYear],
DATENAME(month, DATEADD(week, LEFT(WorkWeek, 2) - 1, DATEADD(wk,
DATEDIFF(wk, - 1, DATEADD(yy, DATEDIFF(yy, 0, GETDATE()), 0)), 0))) AS
[WorkMonth]
FROM tbl_WorkWeek
所需的输出:
[WorkWeek] | [WorkMonth] | [WorkYear]
---------------------------------------
1 | 47-2018 | November | 2018
2 | 1-2019 | January | 2019
3 | 36-2018 | September | 2018
答案 0 :(得分:0)
您可以尝试以下操作-使用charindex() and substring()
函数
SELECT WorkWeek,
RIGHT(WorkWeek, 4) AS [WorkYear],
DATENAME(month, DATEADD(week, substring(WorkWeek,0,charindex('-',WorkWeek)) - 1, DATEADD(wk,
DATEDIFF(wk, - 1, DATEADD(yy, DATEDIFF(yy, 0, GETDATE()), 0)), 0))) AS
[WorkMonth]
FROM tbl_WorkWeek