Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a hardcoded date parameter for use in a query?

Example (not working like this):

SELECT * FROM User 
WHERE LastActivity > Date(1980,1,1)

Where Date should use the parameters year, month, day as integer numbers. To avoid troubles with locales, I explicitly do not want to use a string like "yyyy/mm/dd" or similar.

I am working with Microsoft SQL Server Management Studio on an MSSQL Database, if this matters.

Note: I am sure this is trivial, but I could not find the solution neither using google or SO.

like image 620
Marcel Avatar asked Dec 11 '12 13:12

Marcel


People also ask

How do you write a date parameter in SQL?

SQL Date Data TypesDATE - format YYYY-MM-DD. DATETIME - format: YYYY-MM-DD HH:MI:SS.

How do you Hardcode a timestamp in SQL?

create table foo(a timestamp); insert into foo (a) values ('12/31/2012'); insert into foo (a) values (cast ('12/31/2012' as sql_timestamp)); insert into foo (a) values (cast ('2012-12-31' as sql_timestamp)); insert into foo (a) values (convert('12/31/2012', sql_timestamp)); insert into foo (a) values (convert('2012-12- ...


2 Answers

To avoid troubles with locales, I explicitly do not want to use a string like "yyyy/mm/dd" or similar.

To avoid this, the best way is passing the date as language-neutral like YYYYMMDD. This way it will be language independent:

SELECT * FROM User 
WHERE LastActivity > '19800101';
like image 137
Mahmoud Gamal Avatar answered Sep 21 '22 13:09

Mahmoud Gamal


Use ISO date format which is yyyymmdd

SELECT * FROM User 
WHERE LastActivity > CONVERT(DATE, (CONVERT(VARCHAR(4), @Year) + 
                                    RIGHT('0' + CONVERT(VARCHAR(2), @Month),2) + 
                                    RIGHT('0' + CONVERT(VARCHAR(2), @Date),2) ))
like image 26
Kaf Avatar answered Sep 20 '22 13:09

Kaf