I am getting value from store procedure in date is 3/25/13 10:06:38 AM and i want to convert this 03/25/2013 10:18:28 . How can i convert this in sql server . Because when i cast this in date time i am getting error . Below #PODTimeOnly is varchar(255) Here i am casting only time and after this i want to cast and store date in another variable.
SET #PODTimeOnly = cast(#PODTime as time)
ERROR MSG :
Conversion failed when converting date and/or time from character string.
Thanks
Not sure I totally understand the desired output, but if you're forced to hack strings together to generate differently formatted datetime values, this may work.
DECLARE #strDate VARCHAR(50) = '3/25/13 10:06:38 AM',
#dtDate DATETIME,
#DateOnly VARCHAR(255),
#TimeOnly VARCHAR(255),
#output VARCHAR(255)
-- cast to datetime first to verify its a valid date
SET #dtDate = CAST(#strDate AS DATETIME)
-- parse/cast date and time to seperate variables
SET #DateOnly = CONVERT(VARCHAR(255),#dtDate,101)
SET #TimeOnly = CONVERT(VARCHAR(255),#dtDate,108)
-- duct tape them back together in the desired string format
SET #output = #DateOnly + ' ' + #TimeOnly
-- outputs '03/25/2013 10:06:38'
SELECT #output AS 'NewStringDate'
Related
I tried to convert a varchar variable stored in my database as HH:MM:SS to an actual datetime format HH:MM:SS. I did get the value for HH:MM:SS but the attempt also prefixed the YYYY:MM:DD along with the expected result.
Following is the code that I used to convert this varchar value to HH:MM:SS and the result I got.
Code I tried :
DECLARE #Duration Varchar(10)
SET #Duration = '00:01:23'
SELECT CONVERT(datetime, Duration, 8) AS duration
The output I got :
1900-01-01 00:01:23.000
The expected output:
00:01:23
Please let me know what needs to be changed in this. Thank you!
If you want time, why are you converting to datetime? Given the name it shouldn't be surprising you get both date and time. Try:
DECLARE #Duration char(8) = '00:01:23';
SELECT duration = CONVERT(time(0), #Duration);
Results:
duration
00:01:23
Example db<>fiddle
Just keep in mind that time (nor any date/time type) is not meant to represent a duration or interval. Because what happens when your duration or interval exceeds 24 hours?
What you posted is a time, not a date or datetime. A duration isn't a date. The date types are binary, they don't have prefixes.
You can define a time directly with :
Declare #Duration time ='00:01:23'
Or you can cast a string to a time:
Declare #Duration varchar(10)
Set #Duration = '00:01:23'
Select cast(#Duration as time) as duration
or
Declare #Duration varchar(10)
Set #Duration = '00:01:23'
Select convert(time, #Duration,8) as duration
Unfortunately that's not a duration, it's a time of day. It can only store values between 00:00 and 23:59:59.9999999.
SQL Server has no interval/duration type.
Declare #Duration Varchar(10)
Set #Duration = '00:01:23'
select convert(time,#duration,8);
How to convert this "2020-10-19T12:19:04+0530" string to Date or DateTime in SQL Server? I'm getting this error:
Conversion failed when converting date and/or time from character
string.
Here my comment as answer, since it solved your problem:
If you don't have the possibility of changing the input, you can try to add the column to your date-string:
SELECT CAST(CAST(LEFT(#x,LEN(#x)-2) + ':' + RIGHT(#x, 2) AS datetimeoffset) AS DATETIME)
DECLARE #StringDate VARCHAR(40) = '2020-10-19T12:19:04+0530'
SELECT CONVERT(DATETIME2,STUFF(#StringDate,23,0,':')) -- RESULT 2020-10-19 12:19:04.0000000
SELECT CONVERT(varchar, CONVERT(DATETIME2,STUFF(#StringDate,23,0,':')), 101) --RESULT 10/19/2020
Try now what you want.
Below site helps you to format date.
https://www.mssqltips.com/sqlservertip/1145/date-and-time-conversions-using-sql-server/
You may try to convert the input string to datetimeoffset data type using one of the supported string literal formats for datetimeoffset (e.g. YYYY-MM-DDThh:mm:ss+hh:mm). But, in your specific case, you need to add : in the dateimeoffset part of the input text:
DECLARE #datetime varchar(25) = '2020-10-19T12:19:04+0530'
SELECT CONVERT(
datetimeoffset(0),
LEFT(#datetime, LEN(#datetime) - 2) + ':' + RIGHT(#datetime, 2)
)
As a side note, using datetimeoffset data type is probably a better option, because the input string literal contains information about the time zone. After that you can convert this value to other date and time data types.
DECLARE #datetime varchar(25) = '2020-10-19T12:19:04+0530'
SELECT CONVERT(
datetime,
CONVERT(
datetimeoffset(0),
LEFT(#datetime, LEN(#datetime) - 2) + ':' + RIGHT(#datetime, 2)
)
)
Of course, you can get only the datetime part of the input string and convert it to datetime data type:
DECLARE #datetime varchar(25) = '2020-10-19T12:19:04+0530'
SELECT CONVERT(
datetime,
LEFT(#datetime, 19)
)
I have a table that tracks inserts, updates, and deletions to another table. This pattern has been used for years but has suddenly introduced an error when we added tracking of a DATE column.
This is not a string format issue. My input data is in ISO-8601 standard format.
I've cut out all but the necessary parts of the code to demonstrate the issue.
CREATE TABLE dbo.ChangeTrackingTable
(
oldValue VARCHAR(100) NULL,
newValue VARCHAR(100) NULL
);
GO
CREATE PROCEDURE dbo.usp_TestProcedure
(
#name VARCHAR(100),
#dateOfBirth DATE
)
AS
BEGIN
INSERT INTO dbo.ChangeTrackingTable
(
oldValue,
newValue
)
SELECT
List.oldFieldValue,
List.newFieldValue
FROM
(VALUES
(NULL, #name, IIF(#name IS NOT NULL, 1, 0)),
(NULL, #dateOfBirth, IIF(#dateOfBirth IS NOT NULL, 1, 0))
) AS List (oldFieldValue, newFieldValue, hasChanges)
WHERE
List.hasChanges = 1
END;
GO
The VALUES list is used to dynamically determine which columns are being touched.
When I execute the sproc with just the date, everything works fine.
DECLARE #date DATE = GETDATE();
EXEC dbo.usp_TestProcedure
#name = NULL,
#dateOfBirth = #date;
/*
oldValue newValue
NULL 2019-03-27
*/
But if I try to execute it with any value supplied for #name, whether or not a value for #date is supplied, I get the following error.
DECLARE #date DATE = GETDATE();
EXEC dbo.usp_TestProcedure
#name = 'Name',
#dateOfBirth = #date;
--Conversion failed when converting date and/or time from character string.
If I supply hard-coded values directly to the INSERT statement, it works fine. So I can know it's not happening at the table level on insert.
If I add an explicit cast to this line
(NULL, CAST(#dateOfBirth AS VARCHAR(100)), IIF(#dateOfBirth IS NOT NULL, 1, 0))
it works as well.
The problem occurs with DATETIMEOFFSET, DATETIME, and DATETIME2 types as well, so my use of DATE is not the issue.
My question is why am I getting a string > datetime conversion error when I'm trying to read a DATE value to be inserted into a VARCHAR column, but only in a VALUES list when there exists another non-date value in the result-set for List?
In refining the question itself to its basic structure, I discovered the underlying answer.
When using the pattern
SELECT *
FROM
(VALUES
(NULL, #name, IIF(#name IS NOT NULL, 1, 0)),
(NULL, #dateOfBirth, IIF(#dateOfBirth IS NOT NULL, 1, 0))
) AS List (oldFieldValue, newFieldValue, hasChanges)
SQL Server will need to create a table in memory, and each of those columns needs an assigned datatype. This datatype is not assigned arbitrarily, but methodically according to a well-documented order of Data Type Precedence.
All the date-types appear very high in this list, so my use of DATE takes precedence over any CHAR or VARCHAR type that also appears in the table.
The column in my List table is assigned the highest-precedence type: DATE.
The error is being thrown when the VARCHAR value, 'Name' is being implicitly cast to the data-type of the column, which is DATE. Not when the #date parameter is inserted into the VARCHAR column of the table.
Here is my code:
declare #fdate varchar(50)
declare #tdate varchar(50)
declare #diff int
declare #CalFromdate datetime
declare #CalTodate datetime
set #diff = 360
set #fdate = '2016-12-19 09:30:00'
set #CalFromdate = DATEADD(mi,#diff,CONVERT(DATETIME, #fdate))
print #CalFromdate
set #CalTodate = DATEADD(mi,#diff,CONVERT(DATETIME, #tdate))
print #CalTodate
gives me Dec 19 2016 3:30PM as fromdate
I don't want this format.
Either '2016-12-19 09:30:00' or '2016-12-19 09:30:00:0000'. I want to compare my current date getdate() with 2 dates. If I use above output format with my gatedate format, will it work or both should be in same format?
You are only seeing the date in the format Dec 19 2016 3:30PM because that is the completely arbitrary formatting that is applied in SSMS when printing a datetime value.
If you change your code to select instead of print you will return your datetime value in the format 2016-12-19 15:30:00.000 but again, this is just an arbitrary formatting used to display a type of data.
Within your query, your datetime value doesn't actually have a format. It is simply a date and time. Use it in your comparison and worry about the formatting in whatever application you are presenting the data in.
As an aside, you also don't need to bother using convert on your #fdate or #tdate parameters, as you have already specified them as datetime values in your declare statements.
I'm trying to convert some data that has datatype int. However when I tried to convert 200 into year, it throws an error:
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
Code:
declare #MonthStart datetime,
#Day int = 1,
#Month int = 5,
#Year int = 200 /*gives me an error if I input this but when I tried 2016 the code works fine*/
set #MonthStart = Cast(#Month as varchar(10)) +'-'+ Cast(#Day as varchar(10))+'-'+Cast(#Year as varchar(10))
select #MonthStart
I don't know what's the problem on this. Maybe the datetime won't accept this kind of format 200-05-01 as a date format.
As the error pointed out, you have an out-of-range value. The minimum value for DATETIME is:
1753-01-01 00:00:00.000
What you're tring to convert is below the minimum, thus the error.
As commented by marc_s:
And if you're on SQL Server 2008 or newer, you can get around this
problem by using DATETIME2(3) instead of DATETIME. This new datatype
doesn't have those "artificial" range limitations as the old one did.
You can use datetime2 instead of datetime. It supports dates of 1-1-0001 or later. https://msdn.microsoft.com/en-us/library/bb677335.aspx