SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GOALTER  PROCEDURE testproc
@datebegin datetime,
@dateend datetime
ASdeclare @sql nvarchar(4000)set @sql = 'select * from rdrecord where ddate between ''' + @datebegin + ''' and ''' + @dateend + ''''exec(@sql)GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
为什么调用exec testproc @datetime = '2010-1-1', @dateend = '2010-1-31'总是出错:从字符串转换为 datetime 时发生语法错误。

解决方案 »

  1.   

    eclare @sql nvarchar(4000)set @sql = 'select * from rdrecord where ddate between ''' + convert(char,@datebegin,23) + ''' and ''' + convert(char,@dateend,23) + ''''exec(@sql)
      

  2.   

    --需要转为字符串才能拼接,或者直接改参数类型,如下:ALTER  PROCEDURE testproc
    @datebegin varchar(30),
    @dateend varchar(30)
    ASdeclare @sql nvarchar(4000)set @sql = 'select * from rdrecord where ddate between ''' + @datebegin + ''' and ''' + @dateend + ''''exec(@sql)GO
    SET QUOTED_IDENTIFIER OFF 
    GO
    SET ANSI_NULLS ON 
    GO
      

  3.   

    set @sql = 'select * from rdrecord where ddate between ''' + @datebegin + ''' and ''' + @dateend + ''''exec(@sql)================》
    exec('select * from rdrecord where ddate between ''' + @datebegin + ''' and ''' + @dateend + '''')