问题
I am trying to create a stored that will some values, one of the value is column name and a value.
I've tried the following code
create PROC SelectDynamic
@DateFrom DATETIME,
@DateTo DATETIME,
@ColumName NVARCHAR(50),
@ColumID INT
AS
DECLARE @Sql NVARCHAR(MAX)
SET @Sql=
'
SELECT
*
FROM
Ticket t
WHERE t.TicketDate BETWEEN '+ @DateFrom +' AND' + @DateTo+' AND' + @ColumName +'='+ @ColumID
EXEC sp_executesql @Sql
it give me this error Conversion failed when converting date and/or time from character string.
I am not a SQL expert, and it's me first dynamic sql statement
can any one help
Thanks!
回答1:
You have to escape the quotation marks when building a dynamic query.
Thus, your @SQL variable should be something like this
SET @Sql= 'SELECT * FROM Ticket t WHERE t.TicketDate BETWEEN ''' + CAST(@DateFrom AS NVARCHAR) + ''' AND ''' + CAST(@DateTo AS NVARCHAR) + ''' AND ' + @ColumName + '=' + CAST(@ColumID AS NVARCHAR) + ''
Escaping is done by doubling the quotation marks.
You can do a SELECT @SQL after to test if your query has been built correctly.
回答2:
I think TicketDate column is a varchar field and you are storing dates as 13/10/2013 or 10/13/2013 in TicketDate field. if this is the case then you please tell use how are you are storing the TicketDate data then we can help you.
回答3:
Change your where condition to this. Also print it before executing and correct the number ' used here.
WHERE t.TicketDate BETWEEN '''+ Convert(varchar,@DateFrom) +'''' AND''' + Convert(varchar,@DateTo)+'''' AND''' + @ColumName +''''='''+ Convert(varchar,@ColumID)+''''
回答4:
Try this
declare @DateFrom DATETIME=getdate(),
@DateTo DATETIME=getdate(),
@ColumName NVARCHAR(50)='A',
@ColumID INT=1
DECLARE @Sql NVARCHAR(MAX)
SET @Sql=
'
SELECT
*
FROM
Ticket t
WHERE t.TicketDate BETWEEN '''+ convert(varchar,@DateFrom,110) +''' AND ''' + convert(varchar,@DateTo,110)+''' AND ' + @ColumName +'='+ convert(varchar,@ColumID)
EXEC (@Sql)
Which create the sql string as
SELECT *
FROM Ticket t
WHERE t.TicketDate BETWEEN '10-23-2013' AND '10-23-2013' AND A=1
回答5:
I prefer doing manual substitutions and using parameters
SET @Sql='
SELECT *
FROM Ticket
WHERE TicketDate BETWEEN @DateFrom AND @DateTo
AND {ColumName} = @ColumID
'
SET @Sql = REPLACE(@Sql, '{ColumnName}', QUOTENAME(@ColumnName))
SET @Parameters = '
@DateFrom AS datetime
,@DateTo AS datetime
,@ColumnID AS int
'
EXEC sp_executesql @Sql, @Parameters, @DateFrom, @DateTo, @ColumnID
来源:https://stackoverflow.com/questions/19537166/create-dynamic-where-in-sql-sp