SQL中的转换日期错误

时间:2018-01-12 18:58:11

标签: sql datetime sql-server-2012

执行以下动态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'

2 个答案:

答案 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)

我建议您不能将stringdatetime连接起来 使用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使用适当的数据类型