Getting Error when Comparing Date in SQL Server - sql

I want to compare DateTime field with input
Declare #Where varchar(MAX)
set #Where = #Where + 'EndDate >= ''' + cast('01-01-1970' as datetime) + ''' and EndDate <= ''' + cast('01-01-2200' as datetime) + ''''
print #Where
When I execute this Query I am getting error
Conversion failed when converting date and/or time from character
string.

This should be. You can't concatenate a string with a datetime .
Maybe try this.
Declare #Where varchar(MAX)
set #Where = #Where + 'EndDate >= ''' + cast(cast('01-01-1970' as datetime) as varchar) + ''' and EndDate <= ''' + cast(cast('01-01-2200' as datetime) as varchar) + ''''
print #Where
PS. You add the #Where variable, which is unseted (what means the value of #Where is NULL), to the constant values. And the result of adding NULL with something else is NULL.
maybe try this
Declare #Where varchar(MAX)
set #Where = 'EndDate >= ''' + cast(cast('01-01-1970' as datetime) as varchar) + ''' and EndDate <= ''' + cast(cast('01-01-2200' as datetime) as varchar) + ''''
print #Where

The main issue is, you are trying to concatenate string data with datetime data. Presumably, you want to produce the string
EndDate >= '01-01-1970' and EndDate <= '01-01-2200'
Within your current statement you have
+ cast('01-01-1970' as datetime)
+ cast('01-01-2200' as datetime)
This will take a date in string form and convert it to datetime datatype--which, internally, is an 8 byte binary value. You then try to concatenate that with a string, and SQL is unable to do that. To fix this, start with your string:
set #Where = 'EndDate >= ''' + cast('01-01-1970' as datetime) + ''' and EndDate <= ''' + cast('01-01-2200' as datetime) + ''''
remove the unnecessary cast statements:
set #Where = 'EndDate >= ''' + '01-01-1970'+ ''' and EndDate <= ''' + '01-01-2200' + ''''
which can further be simplified to:
set #Where = 'EndDate >= ''01-01-1970'' and EndDate <= ''01-01-2200'''
One other thing, you have
Declare #Where varchar(MAX)
Set #Where = #Where + <etc>
#Where is initialized as NULL, and when you concatenate (add) your configured string to it, the result will also be NULL. I’m guessing you are adding a clause to an existing WHERE statement; as this is a “new” clause, I’d recommend adding the appropriate boolean operator here, e.g.
Set #Where = #Where + ' AND ' + <etc>

Related

Error message Conversion failed when converting datetime from character string

ALTER PROCEDURE [dbo].[TEST_01]
(
#StartDate DateTime,
#EndDate DateTime
)
AS
BEGIN
SET NOCOUNT ON;
Declare #sql as nvarchar(MAX);
SET #sql = #sql + ';WITH CTE_ItemDetails
MAX(D.Name) as Name,
SUM(ISNULL(DT.col1, 0)) AS col1,
SUM(ISNULL(DT.col2, 0)) AS col2,
SUM(ISNULL(DT.col3, 0)) AS col3,
GROUPING(D.ItemType) AS ItemTypeGrouping
FROM Items D
INNER JOIN Details DT ON DT.ItemId = D.ItemId
INNER JOIN Report R ON R.ReportId = DT.ReportId
where 1=1'
SET #sql = #sql + ' AND (R.ReportDate >= ' + #StartDate + 'AND R.ReportDate <=' + #EndDate +')'
IF #someOtherVariable is not null
SET #sql = #sql + ' AND R.someColumn IN (''' +replace(#someOtherVariableValues,',','')+''+')'
SET #sql = #sql + 'SELECT col1, col2, col3 FROM CTE_ItemDetails'
EXECUTE (#sql)
END
I have a stored procedure that is similar to the T-SQL code above.
(Note that i have removed lots of code that i feel isn't relevant to the error i'm getting)
I'm getting the below error when i execute it.
Conversion failed when converting datetime from character string.
My parameters have values in below format
exec TEST_01 #StartDate=N'4/1/2016 12:00:00 AM',#EndDate=N'4/30/2016 12:00:00 AM'
It looks like the trouble is in the way i'm dynamically setting the SQL statement at line below
SET #sql = #sql + ' AND (R.ReportDate >= ' + #StartDate + 'AND R.ReportDate <=' + #EndDate +')'
What is the best date formatting i can apply to avoid the error.
You should use parameters via sp_executesql.
But your immediate problem is this line:
SET #sql = #sql + ' AND (R.ReportDate >= ' + #StartDate + 'AND R.ReportDate <=' + #EndDate +')'
It should look more like:
SET #sql = #sql + ' AND (R.ReportDate >= ''' + convert(varchar(10), #StartDate, 121) + ''' AND R.ReportDate <= ''' + convert(varchar(10), #EndDate, 121) +''')' ;
Note the inclusion of explicit type casting to a string and the double single quotes so the date literal is not interpreted as 2016 - 04 - 14 (i.e. 2000).
The better method of using parameters looks like:
SET #sql = #sql + ' AND (R.ReportDate >= #StartDate AND R.ReportDate <= #EndDate)' ;
. . .
exec sp_executesql #sql, N'#StartDate date, #EndDate date)', #StartDate = #StartDate, #EndDate = #EndDate;
It is easier to read the SQL statement. The type issues are handled through parameters. And, the query plan is more readily stashed. Unfortunately, parameters only work for constants, not for column or table names, for instance.

Getting an "out of range value" on a conversion of varchar data type to a datetime data type

The error occurs while stored procedure is executing a function to convert varchar data type into into a datetime data type
Since I cannot debug the SQL statement where the error is occurring, is there a way that I can print the values of the data that which is being converted in the store procedure and causing the out of range error?
Or, how can I find out why is the error occurring?
Code:
BEGIN
DECLARE #MONTH VARCHAR(2) = SUBSTRING(#CASH_DATE_FROM,5,2)
DECLARE #YEAR VARCHAR(4) = SUBSTRING(#CASH_DATE_FROM,1,4)
DECLARE #WORK_FILE VARCHAR(80) = ''
DECLARE #SQL VARCHAR(3000) = ''
-- Create Report Tables
IF (#REPORT_TYPE = '2')
BEGIN
SET #WORK_FILE = 'RRS.STG_PST_COLLECTIONS_REVENUE_01'
-- print data
-- select column from table where column not like '%[^0-9]%';
-- Select records from Staging 1
SET #SQL = 'INSERT INTO ' + #WORK_FILE +
' SELECT
REPORT_PERIOD, DATA_SET
,RRS.udfConvertDatetime(START_CASH_DATE)START_CASH_DATE
,RRS.udfConvertDatetime(END_CASH_DATE)END_CASH_DATE, TAT_GRP
,RRS.udfConvertDatetime(CASH_DATE)CASH_DATE, REMIT_ID
,RRS.udfConvertDatetime(TRANSACTION_DATE)TRANSACTION_DATE, PAYMENT_AMT
,TAT, TAT_IND, ACCT_NBR, ORIGINAL_IND, CASH_TRANS_DAY_IND, TRANSFERED_TO
,TRANSFERED_TO_TAT_IND, TRANSFERED_TO_ACCT_NBR, TRANSFERED_FROM, TRANSFERED_FR_TAT_IND
,TRANSFERED_FR_ACCT_NBR, AR_RETURN_IND, PYMT_TRANS_ID, UNAPPLIED_APPLIED_IND
,BACKED_OUT_DC_REF_IND, FUND_CODE, BATCH, ONLINE_ENTERED_IND, REMIT_TYPE_CODE, EFT_SW
FROM ' + 'RRS.LBS_28_STAGING_' + #MONTH + '_' + #YEAR + '_1' +
' WHERE AR_RETURN_IND = ' + '''A'''
EXEC (#SQL)
-- Select records from Staging 2
SET #SQL = 'INSERT INTO ' + #WORK_FILE +
' SELECT
REPORT_PERIOD, DATA_SET
,RRS.udfConvertDatetime(START_CASH_DATE)START_CASH_DATE
,RRS.udfConvertDatetime(END_CASH_DATE)END_CASH_DATE, TAT_GRP
,RRS.udfConvertDatetime(CASH_DATE)CASH_DATE, REMIT_ID
,RRS.udfConvertDatetime(TRANSACTION_DATE)TRANSACTION_DATE, PAYMENT_AMT
,TAT, TAT_IND, ACCT_NBR, ORIGINAL_IND, CASH_TRANS_DAY_IND, TRANSFERED_TO
,TRANSFERED_TO_TAT_IND, TRANSFERED_TO_ACCT_NBR, TRANSFERED_FROM, TRANSFERED_FR_TAT_IND
,TRANSFERED_FR_ACCT_NBR, AR_RETURN_IND, PYMT_TRANS_ID, UNAPPLIED_APPLIED_IND
,BACKED_OUT_DC_REF_IND, FUND_CODE, BATCH, ONLINE_ENTERED_IND, REMIT_TYPE_CODE, EFT_SW
FROM ' + 'RRS.LBS_28_STAGING_' + #MONTH + '_' + #YEAR + '_2' +
' WHERE AR_RETURN_IND = ' + '''A'''
EXEC (#SQL)
-- Update TAT_GRP
SET #SQL = 'UPDATE ' + #WORK_FILE +
' SET TAT_GRP = (CASE WHEN SUBSTRING(TAT,1,1) = ' + '''S''' + ' THEN ' + '''SUA''' + ' ELSE ' + '''STF''' + ' END)' +
' WHERE CONVERT(VARCHAR(32),START_CASH_DATE) = '
+ CHAR(39) + CONVERT(VARCHAR(32),RRS.udfConvertDatetime(#CASH_DATE_FROM))+ CHAR(39)
+ ' AND END_CASH_DATE = '
+ CHAR(39)+ CONVERT(VARCHAR(32),RRS.udfConvertDatetime(#CASH_DATE_TO))+CHAR(39)
EXEC (#SQL)
END
This will help you find the records which is having non numeric data:
select column from table where column not like '%[^0-9]%';
The date range for DATETIME datatype is January 1, 1753, through December 31, 9999.
So first check whatever dates that you are passing lies between this date range. Also check if you passing invalid date like 31st April etc.
You can print the dynamic query that you are forming by using PRINT function.
eg. PRINT #SQL
You don't have to convert to varchar.
TRY THIS
dtadmi BETWEEN CONVERT(DATETIME,'+''''+#dt_frm+'''''+' ) AND CONVERT(DATETIME,'+''''+#dt_to+''''+').....
where #dt_frm,#dt_to=storedprocedure parameter

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