November 25, 2019 at 7:10 pm
In the procedure i have date column as datetime2
declare @date datetime2 = null, @CaptureError varchar(100)
when i am logging this variable like below
SET @CaptureError= @CaptureError + ' ,Date: ' + coalesce(@Date, 'NULL')
this is getting error as data types varchar and datetime2 are incompatible in the add operator.
what is the workaround for this?
November 25, 2019 at 7:15 pm
Explicitly convert @Date to CHAR or VARCHAR.
--Vadim R.
November 25, 2019 at 7:29 pm
SET @CaptureError= @CaptureError + ' ,Date: ' + convert(varchar(10), @Date,101)
Is this correct?
November 25, 2019 at 7:31 pm
you were originally planning to handle the null, so this is a bit better:
SET @CaptureError= @CaptureError + ' ,Date: ' + coalesce(convert(varchar(10), @Date,101), 'NULL')
Lowell
November 25, 2019 at 7:34 pm
Yes, but as written you'll get NULL because @CaptureError and @Date are nulls. Assign some values and test it.
--Vadim R.
November 25, 2019 at 7:38 pm
May i know the reason why i get this error The data types varchar and datetime2 are incompatible in the add operator. when i changed variable from date time to datetime2.
November 25, 2019 at 7:53 pm
datatime has an implicit conversion to varchar, based on your locale. datetime2 does not.
the map below from microsoft has some other examples.
Lowell
November 25, 2019 at 8:08 pm
May i know the reason why i get this error The data types varchar and datetime2 are incompatible in the add operator. when i changed variable from date time to datetime2.
It's because of the way that datetime and datetime2 are stored. One of them is big-endian and the other is little-endian (I forget which is which), so you can do addition on one, but not the other.
Drew
J. Drew Allen
Business Intelligence Analyst
Philadelphia, PA
November 26, 2019 at 8:12 pm
Instead of suffering for the type conversion - use CONCAT which will take care of the conversion for you:
Declare @CaptureError varchar(100) = 'This is an error'
, @Date datetime2 = sysdatetime();
Select @CaptureError, @Date, concat(@CaptureError, ', Date: ', @Date);
It even works for NULL...
Declare @CaptureError varchar(100) = 'This is an error'
, @Date datetime2 = Null;
Select @CaptureError, @Date, concat(@CaptureError, ', Date: ', @Date);
If you need an explicit format for the date:
Declare @CaptureError varchar(100) = 'This is an error'
, @Date datetime2 = sysdatetime();
Select @CaptureError, @Date, concat(@CaptureError, ', Date: ', convert(char(10), @Date, 101));
Jeffrey Williams
“We are all faced with a series of great opportunities brilliantly disguised as impossible situations.”
― Charles R. Swindoll
How to post questions to get better answers faster
Managing Transaction Logs
Viewing 10 posts - 1 through 9 (of 9 total)
You must be logged in to reply to this topic. Login to reply