我有以下代码:
DECLARE @monthPassed VARCHAR(MAX)
SET @monthPassed = '2010'
DECLARE @yearPassed VARCHAR(MAX)
SET @yearPassed = '10'
DECLARE @TempDate DATETIME
SET @TempDate = CAST(@monthPassed + '/' + '1' + '/' + @yearPassed AS DATETIME)
DECLARE @TestDate DATETIME
SET @TestDate = DATEADD(MONTH, 1, @TempDate)
这使@TestDate成为11-02-10。我如何总是在本月的第一天返回?
答案 0 :(得分:2)
可能与@monthPassed
和@yearPassed
被忽略有关。在我的最后,切换它们解决了这个问题。
DECLARE @monthPassed VARCHAR(MAX)
SET @monthPassed = '10'
DECLARE @yearPassed VARCHAR(MAX)
SET @yearPassed = '2010'
DECLARE @TempDate DATETIME
SET @TempDate = CAST(@monthPassed + '/' + '1' + '/' + @yearPassed AS DATETIME)
DECLARE @TestDate DATETIME
SET @TestDate = DATEADD(MONTH, 1, @TempDate)
SELECT @TestDate;
结果:
+-------------------------+
| (no column name) |
+-------------------------+
| 2010-11-01 00:00:00.000 |
+-------------------------+
答案 1 :(得分:0)
您将月份分配到年份,反之亦然
答案 2 :(得分:0)
DATEADD(month, DATEDIFF(month, 0, GETDATE()), 0)
答案 3 :(得分:0)
使用适当宽度的变量/参数应突出显示将年份分配给月份变量的问题,反之亦然。
考虑添加验证以确保参数值是数字,有范围等等。
使用'yyyymmdd'格式可以免除区域设置问题:
DECLARE @yearPassed CHAR(4);
SET @yearPassed = '2010';
DECLARE @monthPassed CHAR(2);
SET @monthPassed = '10';
DECLARE @TestDate DATETIME
SET @TestDate = CAST(@yearPassed + @monthPassed + '01' AS DATETIME);