我有一个 sql server 报告,它有开始日期和结束日期日期时间参数,但是当我在其中指定日期时间时,报告显示错误
An error has occurred during report processing.
Exception has been thrown by the target of an invocation.
Conversion failed when converting date and/or time from character string.
在 C# 代码中设置为报告参数时,startdate 参数的值为 6/22/2011 12:00:00,我的存储过程代码为
create PROCEDURE Price
@Startdate datetime = null,
@Enddate datetime = null
AS
declare @sql varchar(8000)
set @sql = 'SELECT CommodityPrice.dtm_Date FROM Commodity
INNER JOIN CommodityPrice ON Commodity.int_CommodityId = CommodityPrice.int_CommodityId where Commodity.vcr_HSCode is not null '
IF (@Startdate <> '')
BEGIN
SET @sql = @sql + ' and CommodityPrice.dtm_Date >= '+ @Startdate
END
IF (@Enddate <> '')
BEGIN
SET @sql = @sql + ' and CommodityPrice.dtm_Date <= '+ @Enddate
END
set @sql = @sql+ ' order by CommodityPrice.dtm_Date desc'
exec (@sql)
如何解决这个问题?我正在创建动态 sql,因为我还有一些其他参数。
请您参考如下方法:
我的建议;不要连接输入 ;p (一如既往)。您仍然可以在 EXEC 中使用参数,尤其是在 sp_ExecuteSQL 中。这将避免所有问题并且允许查询计划重用。
永远不要连接用户输入,即使在 TSQL 中也是如此。始终使用参数,除非绝对不可能这样做。
作为一个简单的例子(特别是为了展示参数名称不需要匹配):
declare @a int = 15, @b datetime = GETUTCDATE()
declare @sql nvarchar(400) = 'select @x, @y'
exec sp_executeSql @sql, N'@x int, @y datetime', @a, @b
我们将@a 和@b 作为参数(映射到@x 和@y)传递给@sql 中的SQL,并以安全、可重用、可缓存的方式执行。
