Created
January 3, 2012 17:40
-
-
Save jrob00/1556003 to your computer and use it in GitHub Desktop.
Using MSSQL to strtodate date ranges
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
DECLARE @StartDate DATETIME, @EndDate DATETIME | |
SELECT | |
@StartDate = | |
CASE WHEN 'Today' THEN CAST(FLOOR(CAST(GetDate() AS FLOAT)) AS DATETIME) | |
CASE WHEN 'This Week' THEN DATEADD(dd, -1 * (DATEPART(dw, GETDATE()) - 1), CAST(FLOOR(CAST(GETDATE() AS FLOAT)) AS DATETIME)) | |
CASE WHEN 'ThisMonth' THEN DATEADD(dd, -1 * (DATEPART(d, GETDATE()) - 1), CAST(FLOOR(CAST(GETDATE() AS FLOAT)) AS DATETIME)) | |
ELSE '1/1/1900' | |
END | |
SELECT | |
@EndDate = | |
CASE WHEN 'Today' THEN DATEADD(d, 1, CAST(FLOOR(CAST(GetDate() AS FLOAT)) AS DATETIME)) | |
CASE WHEN 'This Week' THEN DATEADD(d, 7, DATEADD(dd, -1 * (DATEPART(dw, GETDATE()) - 1), CAST(FLOOR(CAST(GETDATE() AS FLOAT)) AS DATETIME))) | |
CASE WHEN 'ThisMonth' THEN DATEADD(m,1,DATEADD(dd, -1 * (DATEPART(d, GETDATE()) - 1), CAST(FLOOR(CAST(GETDATE() AS FLOAT)) AS DATETIME))) | |
ELSE '12/31/9999' | |
END | |
SELECT * FROM articles WHERE creation_date >= @StartDate AND creation_date < @EndDate | |
Yes, it needs to be enclosed in a BEGIN .... END block as a stored procedure or trigger.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Can you globalize variables in MySQL like this?