执行以下动态SQL语句时,出现错误:
从字符串
转换日期和/或时间时转换失败
[ReturnDate]
定义为datetime
,@FromDate
和@ToDate
参数也作为datetime
类型传递。我错过了什么?
Set @SQLString =
'Select
[ID], [ReturnDate], [PolicyNumber]
From
Bil_ReturnsRepository
Where
(' + @PolicyNumber + ' is null or PolicyNumber = (' + @PolicyNumber + '))
and (ReturnDate) >= Convert(date, ' + @FromDate + '))
and (ReturnDate) <= Convert(date, ' + @ToDate + '))
and PaymentAmount > 0.00'
答案 0 :(得分:2)
据推测,您使用的是SQL Server。如果是,请学会使用sp_executesql
。其功能之一是传递参数的能力:
Set @SQLString = '
Select [ID], [ReturnDate], [PolicyNumber]
From Bil_ReturnsRepository
Where (@PolicyNumber is null or PolicyNumber = @PolicyNumber) and
(ReturnDate >= @p_FromDate) and
(ReturnDate <= @p_ToDate) and
PaymentAmount > 0.00
';
declare @p_fromdate date;
declare @p_todate date;
select @p_fromdate = convert(date, @fromdate),
@p_todate = convert(date, @todate);
exec sp_executesql @sql,
N'@p_fromdate date, @p_todate date, @policynumber int',
@p_fromdate=@p_fromdate, @p_todate=@p_todate, @policynumber=@policynumber;
如果@p_fromdate
和@p_todate
已经拥有正确的类型,则不需要变量@fromdate
和@todate
。
答案 1 :(得分:1)
我建议您不能将string
与datetime
连接起来
使用sp_executesql
来参数化动态sql
declare @SQLString nvarchar(max)--should be nvarchar
Set @SQLString =
'Select
[ID]
,[ReturnDate]
,[PolicyNumber]
From Bil_ReturnsRepository
Where
(@PolicyNumber is null or PolicyNumber = @PolicyNumber) and
ReturnDate >= @FromDate and
ReturnDate <= @ToDate and
PaymentAmount > 0.00'
exec sp_executesql @SQLString,
N'@FromDate datetime, @ToDate datetime, @PolicyNumber int',
@FromDate, @ToDate, @PolicyNumber
通过这种方式,如果没有如此多的字符串连接,您的查询会更安全,更清晰。
注意:在@PolicyNumber
sp_executesql
使用适当的数据类型