How to set a DateTime variable in SQL Server 2008? - sql

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.

You need to enclose the date time value in quotes:
DECLARE #Test AS DATETIME
SET #Test = '2011-02-15'
PRINT #Test

First of all - use single quotes around your date literals!
Second of all, I would strongly recommend always using the ISO-8601 date format - this works regardless of what your locale, regional or language settings are on your SQL Server.
The ISO-8601 format is either:
YYYYMMDD for dates only (e.g. 20110825 for the 25th of August, 2011)
YYYY-MM-DDTHH:MM:SS for dates and time (e.g. 2011-08-25T14:15:00 for 25th of AUgust, 14:15/2:15pm in the afternoon)

Try using Select instead of Print
DECLARE #Test AS DATETIME
SET #Test = '2011-02-15'
Select #Test

2011-01-15 = 2011-16 = 1995. This is then being implicitly converted from an integer to a date, giving you the 1995th day, starting from 1st Jan 1900.
You need to use SET #test = '2011-02-15'

Just to explain:
2011-02-15 is being interpreted literally as a mathematical operation, to which the answer is 1994.
This, then, is being interpreted as 1994 days since the origin of date (Jan 1st 1900).
1994 days = 5 years, 6 months, 18 days = June 18th 1905
So, if you don't want to to the calculation each time you want compare a date to a particular value use the standard: Compare the value of the toString() function of date object to the string like this :
set #TEST ='2011-02-05'

You want to make the format/style explicit and don't rely on interpretation based on local settings (which may vary among your clients infrastructure).
DECLARE #Test AS DATETIME
SET #Test = CONVERT(DATETIME, '2011-02-15 00:00:00', 120) -- yyyy-MM-dd hh:mm:ss
SELECT #Test
While there is a plethora of styles, you may want to remember few
126 (ISO 8601): yyyy-MM-ddThh:mm:ss(.mmm)
120: yyyy-MM-dd hh:mm:ss
112: yyyyMMdd
Note that the T in the ISO 8601 is actually the letter T and not a variable.

You Should Try This Way :
DECLARE #TEST DATE
SET #TEST = '05/09/2013'
PRINT #TEST

1. I create new Date() and convert her in String .
2. This string I set in insert.
**Example:** insert into newDate(date_create) VALUES (?)";
...
PreparedStatement ps = con.prepareStatement(CREATE))
ps.setString(1, getData());
ps.executeUpdate();
...}
private String getData() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M-dd hh:mm:ss");
return sdf.format(new java.util.Date());
}
**It is very important format** = "yyyy-M-dd hh:mm:ss"

The CONVERT function helps.Check this:
declare #erro_event_timestamp as Timestamp;
set #erro_event_timestamp = CONVERT(Timestamp, '2020-07-06 05:19:44.380', 121);
The magic number 121 I found here: https://www.w3schools.com/SQL/func_sqlserver_convert.asp

Related

Dutch varchar date issue in SQL server 13 month

I have the following datetime format ( as varchar ) in my database 13-04-2018 1:05:00.
I need to convert it to the following format: 2018-04-13 01:05:00. As datetime.
Normal convert functions can't do this because they try to take the 13th month, and that month doesn't exist. This error:
The conversion of a varchar data type to a datetime data type resulted
in an out-of-range value.
Does someone know how to convert this date issue?
Using datetimes is always a pain regardless of the language because of all the different formats across the world.
To sort your issue out currently, you need to use a format style which is a third parameter to CONVERT. Personally what I would suggest here is to store as a datetime, because storing datetimes as strings is never a good idea. It just gets too messy later on, but if saved in the format you would like, it would be saved as yyyy-MM-dd hh:mm:ss
SELECT CONVERT(DATETIME, '13-04-2018 1:05:00',103)
You can create your own function to format it in your desired output string.
CREATE FUNCTION FormatMyDate
(#Date DATETIME) RETURNS VARCHAR(20)
AS
BEGIN
RETURN FORMAT(#Date,'yyyy-dd-MM hh:mm:ss')
END
And then you can call it in SELECT statements like this:
SELECT dbo.FormatMyDate(yourDateCol)
FROM yourTable
this takes the date from the format where month comes before day and reverses the 2 values (month and day)
SELECT CONVERT(DATETIME, '2018-13-04 01:05:00', 103);
Results:
2018-04-13 01:05:00.000
This should work for you requirement...
SELECT FORMAT(yourdate, 'yyyy-dd-MM')
Your Solution Bro...
DECLARE #d DATETIME = GETDATE()
SELECT FORMAT ( #d, 'MM-dd-yyyy hh:mm:ss', 'de-de' ) AS 'Hoping your result'

How to convert every column in a table to date time? Mon d yyyy hH:mmAM

I'm trying to update every column in a table to Datetime (yyyy-mm-dd hh:mm:ss.mmm) from mon dd yyyy hh:mmAM. I've wrote a script that affects columns however no column seem to get updated.
UPDATE ParadataDetail
SET Value = Convert(datetime, Value, 120)
WHERE MetaDataId = 29
Your best option would be to change the data type of the Value column to DateTime. If that's impossible for some reason, and you really, and I do mean really must keep datetime values in a varchar column, and you need to change the string representation of the datetime value, you can use a double conversion:
UPDATE ParadataDetail
SET Value = Convert(varchar(2048), Convert(datetime, Value, 100), 120)
WHERE MetaDataId = 29
If your sql server version is 2012 or higher, you better use Try_convert:
UPDATE ParadataDetail
SET Value = Convert(varchar(2048), Try_Convert(datetime, Value, 100), 120)
WHERE MetaDataId = 29
This will set all the values that can't be converted to datetime as null.

Char to DateTime Conversion

I have one column capturedatetime(Char(30)):
2006-04-25T15:50:59.997000 PM
And I want to convert it and load it at other table column which have is in DateTime. either by T-sql or SSIS which ever way.
I have tried with:
select CONVERT(datetime, '2006-04-25T15:50:59.997000 PM', 126)
But it creates an error:
Conversion failed when converting date and/or time from character string
Late update:
In this column I also have other data that is in a completely different format:
29-JAN-10 08.57.41.000000 PM
(1) STOP storing datetime data in string columns! This is nothing, nothing, nothing but trouble.
(2) Why on earth does your column get data in two different string formats that aren't even valid? Why does the string use 24 hour time and have AM/PM suffix? Why use a regional string format and Y2K disaster like 29-JAN-10?
Here is one way, but it's awfully ugly. I highly recommend you fix the SSIS process to give you valid datetime values in the first place, if not as datetimes, at least as valid ISO strings (yyyy-mm-ddThh:mm:ss.nnn):
DECLARE #x TABLE (d CHAR(30));
INSERT #x SELECT '2006-04-25T15:50:59.997000 PM'
UNION ALL SELECT '29-JAN-10 08.57.41.000000 PM';
SET LANGUAGE ENGLISH; -- this is important, else style 6 may not work
SELECT
CASE WHEN d LIKE '__[0-9]%' THEN
CONVERT(DATETIME, LEFT(d, 23))
WHEN d LIKE '[0-9][0-9]-%' THEN
CONVERT(DATETIME, CONVERT(CHAR(8),
CONVERT(DATETIME,REPLACE(LEFT(d,9),' ','-'),6),112)
+ ' ' + REPLACE(SUBSTRING(d,11,8),'.',':')
+ ' ' + RIGHT(RTRIM(d),2))
END
FROM #x;
The conversion for 126 requires no spaces ... I've got it to work like this:
declare #T varchar(50)
declare #dt datetime
set #T = '2006-04-25T15:50:59.997'
set #dt = convert(datetime,#t,126)
select #T, #dt
select convert(datetime,left('2006-04-25T15:50:59.997000 PM',23))
or
select convert(datetime,left(capturedatetime,23))
If you use cast, you do not even need to supply a format. Code snippet below tested on SQL 2012 Developer version.
declare #var_string varchar(50) = '2006-04-25T15:50:59.997';
declare #var_datetime datetime = cast(#var_string as datetime);
select #var_string as my_string, #var_datetime as my_variable;

Query: Assigning error datetime2

I want to assign '1392-04-31' using this code:
DECLARE #t DATETIME
SET #t = '92-04-31'
I see this error:
Conversion failed when converting date and/or time from character string.
Any one know why?
The solution is:
use datetime2!
DECLARE #t datetime2
SET #t = '1392-04-30'
Because you can't use datetime:
The minimum date stored in datetime is January 1, 1753. So 1392 is not storeable.
April has 30 days.
Using formatted date with datetime:
Second, when you write a date in Sql Server, the format I prefer is {d 'YYYY-MM-DD'}, so in your case becomes:
DECLARE #t DATETIME
SET #t = {d '1992-04-30'}
To complete this discussion, if you want use hh mm ss so you must use this format: {ts 'yyy-mm-dd hh:mm:ss.mmm'}
DECLARE #t DATETIME
SET #t = {ts '1992-04-30 23:59:59.123'}
try this :
declare #t DATETIME
set #t = '1992-04-30 10:54:30'
The date you are trying to set is probably invalid.
Also there are several ways of representing dates in SQL as a string, depending on Language, Dateformat and other setting. Typically the safest way to do this is to use the 'YYYYMMDD' format.
The article below will also answer the question : Why is 1753 the earliest date for datetime?
You should read this if you would like some detailed information:
http://karaszi.com/the-ultimate-guide-to-the-datetime-datatypes
First of all, April only has 30 days. I'm not going to take the time to look up historically whether that was the case in 1392, but either way I'm pretty sure the date 4/31/1392 is invalid for a SQL Server DATETIME.
Also, you should use the full year in the format '01-01-2013'.
Try the following and you'll get the output Jan 1 2013 12:00AM.
declare #t DATETIME
set #t = '01-01-2013'
PRINT #t
The above should work for any valid date.

dateadd - finding a date in the past

I have an odd problem with subtracting 18 months from a date.
Consider the following snippet:
Convert(dateTime,CREATION_DATE,103) >
DateAdd (MONTH, -18, Convert (DateTime, #IN_ACTIVITY_DATE, 103))
This forms part of a where clause in a stored procedure. When I run:
exec theSP #IN_ACTIVITY_DATE = '21/02/2013'
it runs fine, but when I change it to this:
exec theSP #IN_ACTIVITY_DATE = '21/01/2013'
it breaks with the error:
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
Does anyone have any thoughts on why it might be January (all other months are ok) that is breaking my code?
Thanks.
DS
To pass string as datetime use ISO format as yyyymmdd which guaranteed to work in any server with any culture info.;
exec theSP #IN_ACTIVITY_DATE = '20130121'
Also as a side note, if CREATION_DATE is already datetime then you don't need to CONVERT CREATION_DATE for comparison.
--if CREATION_DATE is DATETIME/DATE column
CREATION_DATE >
DateAdd (MONTH, -18, Convert (DateTime, #IN_ACTIVITY_DATE))
Specify the date in YYYY-MM-DD format.
Eg.:
exec theSP #IN_ACTIVITY_DATE = '2013-01-21'
Also, you can use SET DATEFORMAT to specify the date format:
Eg.:
SET DATEFORMAT dmy;
exec theSP #IN_ACTIVITY_DATE = '21/02/2013'
exec theSP #IN_ACTIVITY_DATE = '21/01/2013'
SET DATEFORMAT: Sets the order of the month, day, and year date parts for interpreting date, smalldatetime, datetime, datetime2 and datetimeoffset character strings.
SET DATEFORMAT { format | #format_var }
format | #format_var: Is the order of the date parts. Valid parameters are mdy, dmy, ymd, ydm, myd, and dym.
There might be something in your database, perhaps a check constraint, that doesn't like the January date. The conversion to seems to work on SQL Server 2008 (Fiddle). Something else might be causing the problem.
Also, the date formatting suggestions provided by the others are good advice.