Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a DateTime variable in SQL Server 2008?

Tags:

sql

datetime

SQL Server 2008 is not doing what I expected with DateTime. It doesn't let me set DateTime variables, no matter what date format I use.

When I execute:

DECLARE @Test AS DATETIME SET @Test = 2011-02-15 PRINT @Test 

I get an output of:

Jun 18 1905 12:00AM 

I've checked all of the regional settings that I can find & it all appears okay. I've also tried setting the DateTime to various literal alternatives, such as '15/02/2011', '2011-02-15 00:00:00', etc.

like image 953
Bob Avatar asked Aug 25 '11 09:08

Bob


People also ask

How do you DECLARE a datetime variable in SQL Server?

To declare a date variable, use the DECLARE keyword, then type the @variable_name and variable type: date, datetime, datetime2, time, smalldatetime, datetimeoffset. In the declarative part, you can set a default value for a variable. The most commonly used default value for a date variable is the function Getdate().

How do I set date time in SQL?

To update with the current date and time: UPDATE table_name SET date_field = CURRENT_TIMESTAMP; To update with a specific date value: UPDATE table_name SET date_field = 'YYYY-MM-DD HH:MM:SS.

What is datetime data type in SQL Server?

What is the datetime data type? In SQL, datetime date data type is used for values that contain both date and time. Microsoft defines it as a date combined with a time of day with fractional seconds that is based on a 24-hour clock.


1 Answers

You need to enclose the date time value in quotes:

DECLARE @Test AS DATETIME   SET @Test = '2011-02-15'  PRINT @Test 
like image 171
DaveRead Avatar answered Sep 19 '22 05:09

DaveRead