Error when converting dynamic offset and datetime - sql

I have a dynamic parameter for offset and datetime.
And I have problem when converting the date.
Declare #STR NVARCHAR (MAX)
Declare #offset nvarchar = '+05:00'
Declare #paramrequest date = '2017-03-30'
SET #STR = 'select .... where '
+ CONVERT(DATE, SWITCHOFFSET(CONVERT(DATETIMEOFFSET, + 'REQUESTDATETIME'), #offset )) + ' >=' + CAST(#paramrequest AS DATE);
EXECUTE (#STR)
When I run the script, it gets me this error. How to get fix this error?
Conversion failed when converting date and/or time from character string.

You need to build your string correctly. use CONCAT like this:
SET #STR = CONCAT('select .... where ',
'CONVERT(DATE, SWITCHOFFSET(CONVERT(DATETIMEOFFSET,',
'REQUESTDATETIME),''',
#offset,''' )) >= ''',
CAST(#paramrequest AS DATE), '''')

Related

Concatenate Date in sql Dynamic query

I am trying to execute a dynamic query in which I am concatenating a date but failed in doing
DECLARE #pStartDate datetime
DECLARE #pEndDate datetime
DECLARE #query nvarchar(MAX)
Dynamic query1
set #query = 'Select * from Table1 From tblEvent
Where (EventDate Between' + #pStartDate + ' and ' + #pEndDate +')'
Exec(#query)
Error
Conversion failed when converting date and/or time from character string.
Dynamic query2
set #query = 'Select * from Table1 From tblEvent
Where (EventDate Between' + cast(#pStartDate as varchar) + ' and ' + cast(#pEndDate as varchar) +')'
Exec(#query)
Error
Incorrect syntax near 1 [1 stands for whatever date I passed to #pStartDate]
Please suggest me how to do it.
Thanks.
The really proper way to do this would be to use a parametrized query and having sp_executeSql execute this:
DECLARE #pStartDate datetime
DECLARE #pEndDate datetime
DECLARE #query nvarchar(MAX)
SET #pStartDate = '20080301'
SET #pEndDate = '20080331'
-- if you're setting a NVARCHAR variable - **DO USE** the N'..' prefix!
SET #query = N'SELECT * FROM dbo.Table1
WHERE OrderDate BETWEEN #StartDate AND #EndDate'
-- execute the dynamic SQL, with a list of parameters, and their values
EXEC sp_executesql #query,
N'#StartDate DATETIME, #EndDate DATETIME',
#StartDate = #pStartDate, #EndDate = #pEndDate
In that case, there's no fiddling around with string concatenation and missing quotes and messy stuff like that - just a clear, properly parametrized query that isn't vulnerable to SQL injection attacks, and that performs much better since it's execution plan can be reused for subsequent executions.
Add single quote.
Because date or string specify in single quote like this '12-01-2014'.
set #query = 'Select * from Table1 From tblEvent
Where (EventDate Between''' + #pStartDate + ''' and ''' + #pEndDate +''')'

Convert datetime to yyyymmddhhmmss in sql server

I need to calculate the local time from yyyymmddhhmmss and return it as yyyymmddhhmmss. I have tried the below, it is working but I am not able to get rid of the month name.
Declare #VarCharDate varchar(max)
Declare #VarCharDate1 varchar(max)
Declare #VarCharDate2 varchar(max)
--Declare
set #VarCharDate = '20131020215735' --- YYYYMMDDHHMMSS
--Convert
set #VarCharDate1 =(select SUBSTRING(#VarCharDate,0,5) + '/' + SUBSTRING(#VarCharDate,5,2) + '/' + SUBSTRING(#VarCharDate,7,2) + ' ' + SUBSTRING(#VarCharDate,9,2) +':'+SUBSTRING(#VarCharDate,11,2) +':' + RIGHT(#VarCharDate,2))
select #VarCharDate1
--Convert to Date and Add offset
set #VarCharDate2 = DATEADD(HOUR,DateDiff(HOUR, GETUTCDATE(),GETDATE()),CONVERT(DATETIME,#VarCharDate1,20))
select #VarCharDate2
-- Now we need to revert it to YYYYMMDDhhmmss
--Tried this but month name still coming
Select convert(datetime, #VarCharDate2, 120)
Declare #VarCharDate varchar(max)
Declare #VarCharDate1 varchar(max)
Declare #VarCharDate2 datetime
--Declare
set #VarCharDate = '20131020215735' --- YYYYMMDDHHMMSS
--Convert
set #VarCharDate1 =(select SUBSTRING(#VarCharDate,0,5) + '/' + SUBSTRING(#VarCharDate,5,2) + '/' + SUBSTRING(#VarCharDate,7,2) + ' ' + SUBSTRING(#VarCharDate,9,2) +':'+SUBSTRING(#VarCharDate,11,2) +':' + RIGHT(#VarCharDate,2))
select #VarCharDate1
--Convert to Date and Add offset
set #VarCharDate2 = DATEADD(HOUR,DateDiff(HOUR, GETUTCDATE(),GETDATE()),CONVERT(DATETIME,#VarCharDate1,120))
select #VarCharDate2
-- Now we need to revert it to YYYYMMDDhhmmss
--Tried this but month name still coming
Select convert(datetime, #VarCharDate2, 120)
by using datetime data type you will always have the correct datetime
DECLARE #VarcharDate VARCHAR(14)
DECLARE #VarcharDateWorker VARCHAR(19)
DECLARE #VarcharDateResult VARCHAR(19)
--DECLARE
SET #VarcharDate = '20131020215735' --- YYYYMMDDHHMMSS
SELECT #VarcharDate AS [InputValue]
--Convert String to date format. Adding trailing space to ensure STUFF can validate the string (Length 19 else NULL)
SET #VarcharDateWorker = STUFF(STUFF(STUFF(STUFF(STUFF(STUFF(#VarcharDate+' ',5,0,'-'),8,0,'-'),11,0,' '),14,0,':'),17,0,':'),20,0,'')
SELECT #VarcharDateWorker AS [TransformStage1]
--Check if date is valid (Return Null if date is invalid)
SET #VarcharDateWorker = CASE WHEN ISDATE(#VarcharDateWorker) = 1 THEN #VarcharDateWorker ELSE NULL END
SELECT #VarcharDateWorker AS [TransformStage2]
--Convert to Date and Add offset
SET #VarcharDateWorker = CONVERT(VARCHAR(19),DATEADD(HOUR,DateDiff(HOUR, GETUTCDATE(),GETDATE()),#VarcharDateWorker),120)
SELECT #VarcharDateWorker AS [TransformStage3]
--Cleanout Special Characters to get YYYYMMDDHHMMSS format
SET #VarcharDateResult = REPLACE(REPLACE(REPLACE(#VarcharDateWorker, ' ', ''), '-', ''), ':', '')
SELECT #VarcharDateResult AS [OutputValue]
I think when dealing with Date columns, we need to also be compensating for bad data. Added additional Validation Steps and cleaned-up code
Try this -
Declare #VarCharDate varchar(max)
Declare #VarCharDate1 varchar(max)
Declare #VarCharDate2 varchar(max)
--Declare
set #VarCharDate = '20131020215735' --- YYYYMMDDHHMMSS
--Convert
set #VarCharDate1 =(select SUBSTRING(#VarCharDate,0,5) + '/' + SUBSTRING(#VarCharDate,5,2) + '/' + SUBSTRING(#VarCharDate,7,2) + ' ' + SUBSTRING(#VarCharDate,9,2) +':'+SUBSTRING(#VarCharDate,11,2) +':' + RIGHT(#VarCharDate,2))
select #VarCharDate1
--Convert to Date and Add offset
set #VarCharDate2 = DATEADD(HOUR,DateDiff(HOUR, GETUTCDATE(),GETDATE()),CONVERT(DATETIME,#VarCharDate1,20))
select #VarCharDate2
SELECT REPLACE(REPLACE(REPLACE(CONVERT(VARCHAR(19), CONVERT(DATETIME, #VarCharDate2, 112), 126), '-', ''), 'T', ''), ':', '') [date]
It will return -
date
20131021035700

how to add a date variable in sql string

I have a query that is being built based on some data and I need to be able to add the #StartDate parameter in the string but I get the following error
Conversion failed when converting date and/or time from character string.
Part of the query is like this:
DECLARE #StartDate DATETIME
DECLARE #EndDate DATETIME
DECLARE #where = ''
...
SET #where = #where + '(initDate BETWEEN ' + #StartDate + ' AND ' + #EndDate + ')'
How can I add the StartDate and EndDate there without causing this issue? I tried CONVERT(DATETIME, #StartDate) , but get the same issue
Try this
SET #where = #where + '(initDate BETWEEN ' + convert(varchar(10),#StartDate,104) + ' AND ' + convert(varchar(10),#EndDate,104) + ')'
OR
SET #where = #where + '(initDate BETWEEN ' + convert(varchar(10),#StartDate,106) + ' AND ' + convert(varchar(10),#EndDate,106) + ')'
Just use CAST or CONVERT to change #StartDate and #EndDate to a string. Choose an appropriate method as per the link that gives you the level of precision you need.

Conversion date and/or time from character string

I have a big procedure which consists mostly dynamic SQL. I am having issues with setting one of the date fields.
DECLARE #WorkDate DATETIME
SET #WorkDate = 'SELECT MIN(__Insert_Date) FROM ' + #DatabaseName + '.'
+ #SchemaName + '.' + #TableName + '_Hist'
SET #WorkDate = DATEADD(DAY, DATEDIFF(DAY, '19000101', #WorkDate), '19000101')
This is part of a big procedure. So when I execute the above query I am getting this error:
Msg 241, Level 16, State 1, Line 68
Conversion failed when converting date and/or time from character string.
#WorkDate is DATETIME and your setting it at as a sting thats why the conversion is failing
EDIT :
Try this:
DECLARE #WorkDate DATETIME, #WorkDateString varchar(100)
SET #WorkDateString = 'SELECT MIN(__Insert_Date) FROM ' + #DatabaseName + '.'
+ #SchemaName + '.' + #TableName + '_Hist'
SET #WorkDate = DATEADD(DAY, DATEDIFF(DAY, '19000101', #WorkDate), '19000101')
If you need to insert the #WorkDate into the select string where __Insert_Date is then you need to reverse the order to look like this
DECLARE #WorkDate DATETIME, #WorkDateString varchar(100)
SET #WorkDate = DATEADD(DAY, DATEDIFF(DAY, '19000101', #WorkDate), '19000101')
SET #WorkDateString = 'SELECT MIN(' + CAST(#WorkDate as varchar(19)) + ') FROM ' + #DatabaseName + '.'
+ #SchemaName + '.' + #TableName + '_Hist'
Don't know if you looking to insert the #WorkDate into the select string but that's how you could accomplish that
It looks like the date field in this database is not stored as a DateTime value.
Instead of 19000101, use 1900-01-01. It is unable to recognize your date formate for your character string or your #WorkDate value is not valid.

Unable to inject smalldatetime into D-SQL statement

when i try to execute this sql statement i am getting the error.. Conversion failed when converting character string to smalldatetime data type.
Does anyone know what i am doing wrong?
declare #modality varchar(50)
declare #datefrom smalldatetime
set #modality = 'xxxxxxx'
set #datefrom = '20090101'
declare #var1 nvarchar(4000)
select #var1 =
'select
sum('+ #modality +') as ' + dbo.fnc_titlecase(#modality) +'
from dbo.vw_RawData
where vw.date >= ' + #datefrom + ''
exec sp_executesql #var1
You are trying to concatenate the smalldatetime with a varchar.
Change
Solution 1
declare #datefrom smalldatetime
to
declare #datefrom varchar(8)
and
select #var1 = 'select sum('+ #modality +') as ' + dbo.fnc_titlecase(#modality) +
' from dbo.vw_RawData where vw.date >= ' + #datefrom + ''
to
select #var1 = 'select sum('+ #modality +') as ' + dbo.fnc_titlecase(#modality) +
' from dbo.vw_RawData where vw.date >= ''' + #datefrom + ''''
Solution 2
change
select #var1 = 'select sum('+ #modality +') as ' + dbo.fnc_titlecase(#modality) +
' from dbo.vw_RawData where vw.date >= ' + #datefrom + ''
to
select #var1 = 'select sum('+ #modality +') as ' + dbo.fnc_titlecase(#modality) +
' from dbo.vw_RawData where vw.date >= ''' + convert(varchar(10), #datefrom, 121) + ''''
In the statement select #var1 = 'select sum('+ #modality +') as ' + dbo.fnc_titlecase(#modality) +' from dbo.vw_RawData where vw.date >= ' + #datefrom + '' SQL Server is trying to do date arithmetic by casting all the surrounding strings to a smalldatetime instead of converting #datefrom to a string and performing string concatenation.
Possible fixes.
Change #DateFrom to a sting so that
the concatenation works. Note you
will have to add some quotes so that
the string in #Var1 is properly
formated.
Use convert function to convert #datefrom to a string. Look up the right conversion number in Books online. I don't have time to right now. Don't use cast, it won't give a
Use a paramertized SQL String. Look up sp_executesql in Books Online. (Or wait, StackOverflow always has someone to point out how to avoid dynamic SQL.)
EDIT: Just checked. cast(#DateTime as Varchar(...)) gives a string that I thought might be hard to parse, but it seems to work, might try that instead of convert. Make sure the varchar() is big enough