I have a line in my SQL Stored Procedure that looks like this (works as intended):
HAVING oh.startdate BETWEEN @startDate AND @endDate
However, further down I have the line:
AND (oh.user IN (@userIDs))
Where @userIDs is a comma delimited string of ID’s and oh.user is an INTEGER, so I must actually put the entire SQL query into a dynamic string (@sql) with all the parameters concatenated into it and then use
sp_executesql @sql
Everything is working fine except the BETWEEN dates, I’ve tried a few ways and keep getting errors or no results returned when there should be:
HAVING oh.startdate BETWEEN CONVERT(DATETIME, '+LEFT(CONVERT(VARCHAR, @startDate, 120), 10)+', 120) AND CONVERT(DATETIME, '+LEFT(CONVERT(VARCHAR, @endDate, 120), 10)+', 120)
returns nothing.
HAVING oh.startdate '+LEFT(CONVERT(VARCHAR, @startDate, 120), 10)+' AND '+LEFT(CONVERT(VARCHAR, @endDate, 120), 10)+'
also returns nothing.
HAVING oh.startdate BETWEEN ' + @startDate +' AND '+ @endDate +'
returns error converting DATETIME to string.
Any help is appreciated.
Thanks,
Thomas
You can use
sp_executesqland pass the parameters you want: