开发者

SQL how to make this always return the first of the month

I have the following code:

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)

This makes @TestDate 11-02-10. How would I always make this return the first of the month instead?


Might have something to do with @monthPassed and @yearPassed being inverted. Switching them, on my end, resolved the problem.

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;

Results in:

+-------------------------+
|    (no column name)     |
+-------------------------+
| 2010-11-01 00:00:00.000 |
+-------------------------+


You got the month assigned to the year, and vice versa


DATEADD(month, DATEDIFF(month, 0, GETDATE()), 0)


Using variables/parameters of appropriate width should have highlighted the problem where you are assigning the year to the month variable and vice versa.

Consider adding validation to ensure the parameter values are digits, are with range, etc.

Using the format 'yyyymmdd' provides immunity to regional settings problems:

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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜