Domanda

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

È stato utile?

Soluzione

You can use sp_executesql and pass the parameters you want:

SET @sql = 'SELECT blabla FROM Table WHERE Something HAVING oh.startdate BETWEEN @startDate AND @endDate'
EXEC sp_executesql @sql,N'@startDate DATE, @EndDate DATE',@startDate, @EndDate

Altri suggerimenti

Try this:

HAVING  oh.startdate BETWEEN to_date(@startDate,'dd-MM-yyyy') AND to_date(@endDate,'dd-MM-yyyy')

and change the 'dd-MM-yyyy' to fit the date format you are using.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top