Skip to content

Instantly share code, notes, and snippets.

@jrob00
Created January 3, 2012 17:40
Show Gist options
  • Save jrob00/1556003 to your computer and use it in GitHub Desktop.
Save jrob00/1556003 to your computer and use it in GitHub Desktop.
Using MSSQL to strtodate date ranges
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
@jrob00
Copy link
Author

jrob00 commented Jan 3, 2012

Can you globalize variables in MySQL like this?

@jrob00
Copy link
Author

jrob00 commented Jan 3, 2012

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