SQL cast datetime - sql

In SQL Server 2005, why does:
PRINT Cast('' AS datetime)
display:
Jan 1 1900 12:00AM
I would have thought it should be null?

It's because empty string '' is not NULL. If you do:
select Cast(null AS datetime)
OUTPUT:
-----------------------
NULL
(1 row(s) affected)
CAST and CONVERT (Transact-SQL)
When character data that represents
only date or only time components is
cast to the datetime or smalldatetime
data types, the unspecified time
component is set to 00:00:00.000, and
the unspecified date component is set
to 1900-01-01.

The empty string is casted to 0 which is later casted to the era date.
Unlike Oracle, SQL Server distinguishes between NULL and an empty string.

From experimentation, it looks like SQL Server attempts to cast directly to DateTime, and failing that attempts to cast to int and then to DateTime:
PRINT Cast('2009-1-1' AS datetime)
go
PRINT Cast('2009/1/1' AS datetime)
go
PRINT Cast('1.1' AS datetime)
go
PRINT Cast('1/2009/1' AS datetime)
go
PRINT Cast('' AS int)
go
PRINT Cast(' ' AS int)
go
PRINT Cast(0 AS datetime)
go
PRINT Cast('X' AS datetime)
go
PRINT Cast('X' AS int)
Output:
Jan 1 2009 12:00AM
Jan 1 2009 12:00AM
Msg 241, Level 16, State 1, Line 1
Conversion failed when converting date and/or time from character string.
Jan 1 2009 12:00AM
0
0
Jan 1 1900 12:00AM
Msg 241, Level 16, State 1, Line 1
Conversion failed when converting date and/or time from character string.
Msg 245, Level 16, State 1, Line 1
Conversion failed when converting the varchar value 'X' to data type int.

Related

Convert nvarchar(50) to date format

In a table called mt, how do I convert the Sun column to date format from nvarchar(50)?
Sun
------------------------
Sunday, March 24, 2019
I tried the below query but it errored out.
SELECT CONVERT(DATETIME,Sun,109) FROM [mt]
Msg 241, Level 16, State 1, Line 2
Conversion failed when converting date and/or time from character string.
I think this will work:
select convert(date, stuff(sun, 1, charindex(',', Sun) + 1, ''))

I'm having date conversion problems with the 3rd column in the script below

Select c1.CDS_Date, c2.CDS_Date, Dateadd(day, -1 , c2.CDS_Date)
from cte as c1 left join
cte as c2
on c1.[Local Patient Identifier] = c2.[Local Patient Identifier] and
c1.JoinKey = c2.JoinKey - 1
Can I get come help please?
I got no issues with c1.CDS_Date and c2.CDS_Date.
I receive the following error message as soon as I include the 3rd column:
(24 rows affected)
Msg 242, Level 16, State 3, Line 50
The conversion of a varchar data type to a datetime data type resulted in an --out-of-range value.
That is because your CDS_Date is not of date/datetime type but is a string.
Here is an example:
declare #t table (CDS_Date varchar(100));
insert into #t values ('28/10/2017');
set language British;
select CDS_Date, dateadd(day, -1, CDS_Date) as dt
from #t;
-------
--CDS_Date dt
--28/10/2017 2017-10-27 00:00:00.000
set language us_english;
select CDS_Date, dateadd(day, -1, CDS_Date) as dt
from #t;
--Msg 242, Level 16, State 3, Line 40
--The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
This example shows you that not every string can be converted to date EVEN IF it seems to you that it represents a valid data. This is because server expects a date that you pass as a string to be in the certain format that depends on session language.
To be independent of session language you shoud pass your date string using convert function and specifying the format of your date.
In my example I can fix the issue converting to date with style 103:
select CDS_Date, dateadd(day, -1, convert(date, CDS_Date, 103)) as dt
from #t;
----
--CDS_Date dt
--28/10/2017 2017-10-27
Now it gives me the correct result in both languages just because it knows that my input strings are of 103 format, i.e. dd/mm/yyyy

Convert julian date to date in sql server

I want to convert the julian date in a date format. 
Below, please find an example to create my error. All my dates have 5 digits I need to convert.
create table #test (dateR int)
insert into #test (dateR)
values (39596),(39596),(39595),(39595),(39593),(39592),(39592),(39589),(38104),(38104),(37957)
SELECT * from #test
select *
, dateadd (year, dateR/1000 - 1900, dateR %1000 - 1) as Rd
from #test
Getting the error:
Msg 517, Level 16, State 1, Line 2 Adding a value to a 'datetime'
column caused an overflow.
Also tried:
SELECT DATEADD(dd, CONVERT(int, RIGHT(dateR,3)) - 1, CONVERT(datetime,SUBSTRING(dateR,1,2)+'0101', 212))
This returns:
Msg 8116 level 16 state 1 line 1 nullArgument data type int is invalid for argument of substring function
You can just cast the INT value to a DATETIME.
For example:
SELECT CAST(39596 AS DATETIME); -- Returns 2008-05-30 00:00:00.000

Error converting varchar to datetime in SQL

I want to convert from CRSE_EDTE (string) to datetime. Current CRSE_EDTE date format is YYYYMM, so I decided to put 28 as day for every date (DD).
select
try_convert(datetime, [CRSE_EDTE], 112) + CRSE_EDTE + '28' as new_CRSE_EDTE
FROM
[SMBM_DBPELJ].[DBPELJ].[MSTUMASTER]
I get an error:
Msg 241, Level 16, State 1, Line 1
Conversion failed when converting date and/or time from character string.
I don't have your database to play with, but would something like this work?
select try_convert(datetime,LEFT([CRSE_EDTE], 4)+'-'+RIGHT([CRSE_EDTE],2)+'-28',111) as new_CRSE_EDTE
FROM [SMBM_DBPELJ].[DBPELJ].[MSTUMASTER]

Convert date of format dd mon yyyy to return integer of month in SQL

I have a varchar variable containing value 01 May 2013 and I need to obtain the integer of the Month part.
for eg if 01 May 2013 is input I should get the result as 5
The query I wrote was :
select DATEPART(MM,CONVERT(DATETIME,CONVERT(VARCHAR(15),'01 '+SUBSTRING(FISCAL_MONTH,1,3)+' 2013'),100))
FROM <table name>
Here FISCAL_MONTH is my column name from the table. However this query is showing me the result, for eg 11 for November but is also throwing the following error :
Msg 241, Level 16, State 1, Line 1
Conversion failed when converting date and/or time from character string.
I have tried various combinations, bit in vain. Kindly note I need it in a query. Kindly help.
If that is the only date you want to convert then you can simplify the SQL statement to:
select datepart(mm,convert(datetime,'01 May 2013'))
I just used this to test and it worked:
declare #t as varchar(333)
set #t = '01 May 2013'
select datepart(mm,convert(datetime, #t))
Gives me
5
If you are still getting that conversion error, then you either have some NULL values OR some date values that are not in the correct format. Check the data in your table to see which it is.
I'll leave it to you to add the rest of the months.
select case substring('01 MAY 2013',4,3) when 'JAN' then 1
when 'FEB' then 2
when 'MAR' then 3
when 'APR' then 4
when 'MAY' then 5
when 'JUN' then 6 else 9999 end
It might just be that there is a 3 instead of a 2 in the substring argument:
SUBSTRING(FISCAL_MONTH,1,2)+' 2013'),100))
The concat might work also:
select DATEPART(MM, CONCAT('01/', substring(convert(varchar(15),'03/23/2013'),1,2),'/2013'));
Wow, it is real interesting to see all the weird code that people come up with. I use the KISS policy most of the time (keep it simple stupid).
How about the MONTH() function. It has been in the TSQL language forever. I even threw in a coalesce to handle any unexpected NULLS.
-- Simple date as text
declare #var_test varchar(20) = '01 may 2013';
-- Use coalesce to handle nulls, use month to return int
select month(coalesce(#var_test, '01 jan 1900')) as my_month_index
Select month ( cast ( date_col as datetime ))
From table
You have to convert with proper format, you have to pass the apprpriate format-style value on your conversion. As per MSDN, you are using "dd mon yy" format, so you have to supply the corresponding format-style-code 6 or 106
Declare #FISCAL_MONTH nvarchar(max) = '01 May 2013'
select datepart(mm,Convert(datetime, #FISCAL_MONTH, 6))
--5
Set #FISCAL_MONTH = '01 November 2013'
select datepart(mm,Convert(datetime, #FISCAL_MONTH, 6))
--11