执行以下动态 SQL 语句时,出现错误:
Conversion failed when converting date and/or time from character string
[ReturnDate]
定义为 datetime
,@FromDate
和 @ToDate
参数作为类型传递日期时间
也是如此。我缺少什么?
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'
最佳答案
您可能正在使用 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;
如果 @fromdate
和 @todate
已经具有变量 @p_fromdate
和 @p_todate
则不需要正确的类型。
关于sql - SQL 中的转换日期错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48232450/