Convert NVARCHAR to DATE SQL [closed] - sql

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed last year.
Improve this question
I am having trouble converting this nvarchar to date: I want to convert '2021-02-01 00:00:00.0000000' nvarchar to 2021-02-01 date
DECLARE #var nvarchar(255) = '2021-02-01 00:00:00.0000000'
CONVERT(date, #var, 103)
I have used this convert function but I'm getting:
Conversion failed when converting date and/or time from character string
error. Any help on how to solve this problem?

Try 120 instead of 103. 103 expects a string in the format d/m/y.
DECLARE #var nvarchar(255) = '2021-02-01 00:00:00.0000000';
SELECT CONVERT(date, #var, 120);
Result (db<>fiddle):
2021-02-01
Also:
Why nvarchar? Dates don't need to support Unicode characters.
Try to get the source to correct the format to a standard, unambiguous format, like:
yyyy-mm-ddThh:mm:ss.nnnnnnn
yyyymmdd hh:mm:ss.nnnnnnn
Much more on dates: Dating Responsibly

You can CAST that format directly to a DATE or DATETIME2 type.
DECLARE #var nvarchar(255) = '2021-02-01 00:00:00.0000000'
DECLARE #date date = CAST(#var AS DATE);
SELECT #var as var, #date as [date];
Or even CONVERT it without a format number.
DECLARE #var nvarchar(255) = '2021-02-01 00:00:00.0000000'
DECLARE #datetime2 datetime2 = CONVERT(DATETIME2, #var);
SELECT #var as var, #datetime2 as [datetime2];
But to CAST or CONVERT it to a DATETIME, then it needs to be truncated.
The default format number is 121 (ODBC canonical with milliseconds)
DECLARE #var nvarchar(255) = '2021-02-01 00:00:00.0000000'
DECLARE #datetime datetime = CONVERT(datetime, LEFT(#var, 23), 121);
SELECT #var as var, #datetime as [datetime];

Related

difference in the format of output between datetime and datetime2(3) data types when converted to varchar with style 114

There is a difference between the format of DateTime and DateTime2(3) when they are converted to varchar with style 114. The example is as follows:
DECLARE #date1 datetime=GETDATE()
DECLARE #date2 DATETIME2(3)=GETDATE()
SELECT CONVERT(VARCHAR,#date1, 114),CONVERT(VARCHAR,#date2,114)
The output of the above SQL statements is:
14:47:33:820 14:47:33.820
db<>fiddle.uk
So, we can see the difference in the output is ":" in the case of DateTime whereas "." in the case of DateTime2(3).
Is there any solution to get the ":" in the output in the case of datetime2(3)?
The behavior is unexplainable; as a workaround, you can use the FORMAT function to format the date:
DECLARE #date1 DATETIME = SYSDATETIME()
DECLARE #date2 DATETIME2(3) = SYSDATETIME()
SELECT
#date1,
#date2,
FORMAT(#date1, 'HH:mm:ss:fff'),
FORMAT(#date2, 'HH:mm:ss:fff')
I think you can CAST #date2 AS DATETIME before convert to varchar if you want to get the ":" in the output in the case of datetime2(3)
SELECT CONVERT(VARCHAR,#date1, 114),CONVERT(VARCHAR,CAST(#date2 AS DATETIME),114)
In the meantime, format 113 seems to use the colon correctly, so you can use:
RIGHT(CONVERT(VARCHAR(255), #date2, 113), 12)
Note the use of a length with VARCHAR(). My advice is to never use string types in SQL Server without a length. The default length varies by context and not including an explicit length can introduce a hard-to-debug error.

How to set value on varchar to datetime variable [duplicate]

This question already has answers here:
SQL Server Convert Varchar to Datetime
(9 answers)
Closed 8 years ago.
I have two variables, one is varchar another one is datetime. I need to convert varchar to datetime
declare #startdate as varchar(10)= '1/1/2013 1:60AM'
declare #enddate as varchar(10)= '1/1/2014 1:60AM'
declare #startdTime datetime
set # startdTime =cast(#startdate as datetime)
This conversion however causes an error:
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
How to convert this without error? I see several example on stackoverflow but fail to get solution,need help on this issue.
IF have any query please ask, thanks in advance
The problem with your input string 1:60AM to 1:06AM
declare #startdate as varchar(20)= '1/1/2013 1:06AM'
declare #enddate as varchar(20)= '1/1/2014 1:06AM'
declare #startdTime datetime
SELECT CONVERT( VARCHAR(20), #startdate ,101)
SELECT CAST(CONVERT( VARCHAR(30), #startdate ,101) AS DATETIME)
make Sure about time . is it 1.60AM
declare #startdate as varchar(50)= '01/01/2013 1:00 AM'
declare #enddate as varchar(50)= '01/01/2014 1:00 AM'
declare #startdTime datetime
set #startdTime =cast(#startdate as datetime)
print #startdTime
Here '1/1/2013 01:60 AM' is more than 10 character. Increase it to 20 or more
Like
#startdate AS VARCHAR(25)
#enddate AS VARCHAR(25)
N:B:
There is nothing like '1:60 AM',Make it "2:00 AM" or "1:06 AM"
Different type of Date time formats for MS SQL

convert varchar(ddmmyyyy) to date format

How can I convert, for example, ddmmyyyy which is a varchar(8) to date format(dd/mm/yyyy)?
I have a stored procedure which accepts a date varchar(8) parameter.
I want to convert it to date format before inserting into database.
I tried to use
INSERT INTO mytable(createdDate) VALUES (CONVERT(date, CONVERT(varchar(8), #date), 106));
An error:
Conversion failed when converting date and/or time from character string.
createdDate column is type : date
ddmmyyyy is not a valid date format. You need to first make that string into something that can be parsed as a DATE / DATETIME. The quickest way might be to simply SUBSTRING the pieces into a mm/dd/yyyy format. That does convert successfully. But you have a VARCHAR(8). So you either need to increase that to be VARCHAR(10) (or better yet, just CHAR(10)), or declare a local variable to hold the altered value.
For example:
DECLARE #Date VARCHAR(8); -- input parameter
SET #Date = '25032014';
DECLARE #Date2 CHAR(10);
SET #Date2 = SUBSTRING(#Date, 3, 2)
+ '/' + SUBSTRING(#Date, 1, 2)
+ '/' + SUBSTRING(#Date, 5, 4);
SELECT #Date2, CONVERT(DATE, #Date2);
-- 03/25/2014 2014-03-25
EDIT:
Actually, I found a slightly simpler way. I started out with this method but realized that it did not work with ddmmyyyy as opposed to mmddyyyy. I somehow missed that there was an appropriate date style number for dd/mm/yyyy. So, simply adding two slashes to the incoming string and then calling CONVERT does work, but only if you use 103 as the "style". And like the first solution, it requires either changing the incoming parameter to be VARCHAR(10) or CHAR(10) instead of VARCHAR(8), or creating a local variable to be CHAR(10).
DECLARE #Date VARCHAR(8); -- input parameter
SET #Date = '25032014';
DECLARE #Date2 CHAR(10);
SET #Date2 = STUFF(STUFF(#Date, 3, 0, '/'), 6, 0, '/');
SELECT #Date2, CONVERT(DATE, #Date2, 103); -- 103 = dd/mm/yyyy
-- 25/03/2014 2014-03-25
Conversion "styles" can be found on the MSDN page for CAST and CONVERT.

Conversion failed when converting the nvarchar value '06/30/2012' to data type int

I'm having issues trying to set two variables, a From Date, and a To Date. Once I solve the issue for one, the other will be easy enough to figure out. I'm getting the error:
Conversion failed when converting the nvarchar value '06/30/2012' to data type int.
It's worth noting that I'm using a view to bring various tables together, and then executing the ones I want via sp_executesql. When I print my query I can see that it's recognizing the #fromdate as 0, perhaps that's the issue..
declare #fromdate nvarchar
declare #todate nvarchar
select #fromdate = '03/01/1999'
select #todate = ''
IF #fromdate <> ''
BEGIN
SELECT #sql = #sql + ' and convert (nvarchar,document_Date,101) > '+#fromdate+''
END
if #todate <> ''
BEGIN
SELECT #sql = #sql + ' and convert(nvarchar,document_date,101) > '+#todate+''
END
The column document_date is datetime. Any ideas? If so, could you explain why this is occurring so I can learn and avoid it happening in the future? I've included the print SQL below.
SELECT [system_status]
,[document_status_code]
,[rpt_category]
,[category]
,[user_status_cd]
,[user_status]
,[assigned_to_id]
,[assigned]
,[assigned_to_date]
,[owner_id]
,[owner]
,[rpt_acct_code]
,[acct_name]
,[rpt_title]
,[job_name]
,[logged_time]
,[rpt_format_type]
,[rpt_run_id]
,[rpt_doc_id]
,[rpt_id]
,[rpt_filename]
,[rpt_file_path]
,[rpt_run_name]
,[sla_start_date]
,[sla_due_date]
,[sla_completed_date]
,[sla_status]
,[SLA_Days]
,[Document_Date]
FROM VW_Document_Main
WHERE 1=1 and convert (nvarchar,document_Date,101) > 0
order by document_status_code ,owner_id
Part of the problem is that you do not have a length on your declaration of #fromdate
It is only returning the first character because you do not have a length. The declaration should say:
declare #fromdate nvarchar(10)
declare #todate nvarchar(10)
Since you do not have a length, it is returning 0 which is the first character.
Secondly, you are also comparing string values of the dates, you should be comparing the date values.
declare #fromdate datetime
declare #todate datetime
Then your code could be:
SELECT #sql = #sql + ' and document_Date > '''+convert(varchar(10), #fromdate, 101)+''''
The literal
'03/01/1999'
is a string literal. You are converting document_Date to a varchar, then doing an inequality comparison
and convert (nvarchar,document_Date,101) > '+#fromdate
Since the dates are not formatted YYYYMMDD, the comparison is unlikely to produce the comparison you expect.
If #fromdate for example is '04/01/1900', it will be greater than '03/01/1999' because '04' is greater than '03'.
Instead, convert #fromdate to the same type as document_Date, e.g.
AND document_Date > convert(datetime, #fromdate)
If the column document_date is already a datetime, why not declare declare #fromdate
and #todate as datetime as well, then your code will be simpler and you won't have to do any conversion. It seems to me the conversion is unnecessary for what you are trying to do.
Problem #1
declare #fromdate nvarchar
select #fromdate = '03/01/1999'
Why are you defining these as Unicode strings, never mind strings without a length? Why are you using an ambiguous, unreliable format for the literal? Is that March 1st or January 3rd? Are you sure your instance of SQL Server agrees with you?
Problem #2
SELECT #sql = #sql + ' and convert (nvarchar,document_Date,101) > '+#fromdate+''
Why are you converting your column to a Unicode string, never mind a string without a length? Why are you comparing it as a string? You know that '05/05/2010' is greater than '02/21/2015', when compared as a string, right?
Solution
Stop using ambiguous formats. Stop thinking that dates are strings and should be compared as such.
How about:
DECLARE #fromdate DATETIME = '19990301'; -- guessing you meant March 1st.
-- See why ambiguous formats are bad and you should never use them?
...
SELECT #sql += ' AND document_Date > #fromdate;';
EXEC sp_executesql #sql, N'#fromdate DATETIME', #fromdate;
Now you don't have to do any conversions at all.

Convert varchar into datetime in SQL Server

How do I convert a string of format mmddyyyy into datetime in SQL Server 2008?
My target column is in DateTime
I have tried with Convert and most of the Date style values however I get an error message:
'The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.'
OP wants mmddyy and a plain convert will not work for that:
select convert(datetime,'12312009')
Msg 242, Level 16, State 3, Line 1
The conversion of a char data type to a datetime data type resulted in
an out-of-range datetime value
so try this:
DECLARE #Date char(8)
set #Date='12312009'
SELECT CONVERT(datetime,RIGHT(#Date,4)+LEFT(#Date,2)+SUBSTRING(#Date,3,2))
OUTPUT:
-----------------------
2009-12-31 00:00:00.000
(1 row(s) affected)
SQL Server can implicitly cast strings in the form of 'YYYYMMDD' to a datetime - all other strings must be explicitly cast. here are two quick code blocks which will do the conversion from the form you are talking about:
version 1 uses unit variables:
BEGIN
DECLARE #input VARCHAR(8), #mon CHAR(2),
#day char(2), #year char(4), #output DATETIME
SET #input = '10022009' --today's date
SELECT #mon = LEFT(#input, 2), #day = SUBSTRING(#input, 3,2), #year = RIGHT(#input,4)
SELECT #output = #year+#mon+#day
SELECT #output
END
version 2 does not use unit variables:
BEGIN
DECLARE #input CHAR(8), #output DATETIME
SET #input = '10022009' --today's date
SELECT #output = RIGHT(#input,4) + SUBSTRING(#input, 3,2) + LEFT(#input, 2)
SELECT #output
END
Both cases rely on sql server's ability to do that implicit conversion.
Likely you have bad data that cannot convert. Dates should never be stored in varchar becasue it will allow dates such as ASAP or 02/30/2009. Use the isdate() function on your data to find the records which can't convert.
OK I tested with known good data and still got the message. You need to convert to a different format becasue it does not know if 12302009 is mmddyyyy or ddmmyyyy. The format of yyyymmdd is not ambiguous and SQL Server will convert it correctly
I got this to work:
cast( right(#date,4) + left(#date,4) as datetime)
You will still get an error message though if you have any that are in a non-standard format like '112009' or some text value or a true out of range date.
I found this helpful for my conversion, without string manipulation. https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql
CONVERT(VARCHAR(23), #lastUploadEndDate, 121)
yyyy-mm-dd hh:mi:ss.mmm(24h) was the format I needed.
Convert would be the normal answer, but the format is not a recognised format for the converter, mm/dd/yyyy could be converted using convert(datetime,yourdatestring,101) but you do not have that format so it fails.
The problem is the format being non-standard, you will have to manipulate it to a standard the convert can understand from those available.
Hacked together, if you can guarentee the format
declare #date char(8)
set #date = '12312009'
select convert(datetime, substring(#date,5,4) + substring(#date,1,2) + substring(#date,3,2),112)
Look at CAST / CONVERT in BOL that should be a start.
If your target column is datetime you don't need to convert it, SQL will do it for you.
Otherwise
CONVERT(datetime, '20090101')
Should do it.
This is a link that should help as well:
I'd use STUFF to insert dividing chars and then use CONVERT with the appropriate style. Something like this:
DECLARE #dt VARCHAR(100)='111290';
SELECT CONVERT(DATETIME,STUFF(STUFF(#dt,3,0,'/'),6,0,'/'),3)
First you use two times STUFF to get 11/12/90 instead of 111290, than you use the 3 to convert this to datetime (or any other fitting format: use . for german, - for british...) More details on CAST and CONVERT
Best was, to store date and time values properly.
This should be either "universal unseparated format" yyyyMMdd
or (especially within XML) it should be ISO8601: yyyy-MM-dd or yyyy-MM-ddThh:mm:ss More details on ISO8601
Any culture specific format will lead into troubles sooner or later...
use Try_Convert:Returns a value cast to the specified data type if the cast succeeds; otherwise, returns null.
DECLARE #DateString VARCHAR(10) ='20160805'
SELECT TRY_CONVERT(DATETIME,#DateString)
SET #DateString ='Invalid Date'
SELECT TRY_CONVERT(DATETIME,#DateString)
Link:MSDN TRY_CONVERT (Transact-SQL)
I had luck with something similar:
Convert(DATETIME, CONVERT(VARCHAR(2), #Month) + '/' + CONVERT(VARCHAR(2), #Day)
+ '/' + CONVERT(VARCHAR(4), #Year))
The root cause of this issue can be in the regional settings - DB waiting for YYYY-MM-DD while an app sents, for example, DD-MM-YYYY (Russian locale format) as it was in my case. All I did - change locale format from Russian to English (United States) and voilĂ .
This seems the easiest way..
SELECT REPLACE(CONVERT(CHAR(10), GETDATE(), 110),'-','')
SQL standard dates while inserting or updating Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
So if you are inserting/Updating below 1/1/1753 you will get this error.
DECLARE #d char(8)
SET #d = '06082020' /* MMDDYYYY means June 8. 2020 */
SELECT CAST(FORMAT (CAST (#d AS INT), '##/##/####') as DATETIME)
Result returned is the original date string in #d as a DateTime.