sql server 2008中日期时间参数的转换问题

本文关键字:参数 转换 问题 时间 日期 server 2008 sql | 更新日期: 2023-09-27 18:00:57

我有一个sql server报告,其中包含startdate和enddate日期时间参数,但当我在其中指定日期时间时,报告显示错误

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.

startdate参数的值2011年6月22日12:00:00 AM当在C#代码中设置为报告参数时,我的存储过程代码是

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,因为我还有一些其他参数。

sql server 2008中日期时间参数的转换问题

我的建议;不要连接输入;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,并以安全、可重用、可缓存的方式执行。

在连接之前,必须先将值转换为varchar

CONVERT(varchar(30), @Enddate, 121)

你有第二个问题,因为日期时间永远不能是空字符串:如果你分配了一个空字符串,那么它就变成了1900年1月1日的午夜(零(

第三个问题是,对于动态SQL,您现在需要授予表的权限。如果没有这一点,调用者只需要对存储过程的权限。

最后,您不需要动态SQL

create PROCEDURE Price
   @Startdate datetime = null,
   @Enddate datetime = null    
AS    
SET NOCOUNT ON;
SET @Startdate = ISNULL(@Startdate, '19000101');
SET @Enddate = ISNULL(NULLIF(@Enddate, '19000101'), '99991231');
SELECT CommodityPrice.dtm_Date FROM Commodity 
INNER JOIN CommodityPrice ON Commodity.int_CommodityId = CommodityPrice.int_CommodityId where Commodity.vcr_HSCode is not null ' 
and CommodityPrice.dtm_Date >= @Startdate
and CommodityPrice.dtm_Date <= @Enddate
order by CommodityPrice.dtm_Date desc
GO

您也可以在日期参数后面留下

tableName.DateInTable> @ReportDateParameter

这就是在一个项目中对我有效的方法。

很抱歉,刚才看到您的sql链接在一起,因此您的DateParameter必须转换为字符串,如上面的答案所述。