Reputation: 868
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
Upvotes: 1
Views: 2649
Reputation: 3002
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.
Upvotes: 0
Reputation: 12353
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) + ')'
Upvotes: 2