首页 新闻 会员 周边

存储过程出现”从字符串转换日期和/或时间时,转换失败”错误

0
[待解决问题]

问题如下:

  存储过程中定义了一个时间类型参数,传入之后在存储过程中进行拼接成SQL语句再执行  

复制代码
if exists(select top 1 1 from sysObjects where id=OBJECT_ID('Pro_Test') and type='P')
    drop procedure Pro_Test
go 
Create procedure Pro_Test
(
    @date datetime
)
as 
begin
    declare @where varchar(2000)
    declare @sql varchar(max)

    set @where=' where 1=1 ';
    if ISNULL(@date,'')<>''
    begin
        set @where=@where+' and A.Createtime >'''+@date+''   
    
    end

    set @sql='select * from Table2 A '+@where
    exec(@sql)
end
复制代码

  执行时exec Pro_Test '2017-07-12',报错如下:  

消息 241,级别 16,状态 1,过程 Pro_Test,第 36 行
从字符串转换日期和/或时间时,转换失败。

 

但是在拼接SQL语句时再转换成varchar便可正确执行

set @where=@where+' and A.Createtime >'''+CONVERT(varchar(23), @date,120)+''''

 

疑问:

  参数定义的为datetime类型,正常情况下时间类型也是要通过单引号括起来的,为什么在存储过程拼接就有问题呢?

齐_大圣的主页 齐_大圣 | 菜鸟二级 | 园豆:202
提问于:2017-07-14 18:46
< >
分享
所有回答(2)
0

我觉得你的这句话写错了

set @where=@where+' and A.Createtime >'''+@date+''

应该写成这样:

set @where+=' and A.Createtime >'''+@date+'''';

金琥 | 园豆:2605 (老鸟四级) | 2017-07-15 16:40

 写成那样也是一样的,必须转成varchar类型才能正确执行。

支持(0) 反对(0) 齐_大圣 | 园豆:202 (菜鸟二级) | 2017-07-16 12:56
0

declare @date        datetime

set  @date='2017-08-01'

between @date+' 00:00:00' and @date+' 23:59:59'

不太清楚你日期的格式,我这样拼接没报错

守墓老人 | 园豆:26 (初学一级) | 2017-08-01 12:35
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册