日期:2014-05-18  浏览次数:20539 次

如何将时间变量用到动态SQL中参与时间运算
SQL code
ALTER PROCEDURE [dbo].[output_jkzx]
    @s_db nvarchar(100),
    @d_db nvarchar(100),
    @exec_time int
AS
declare @paramtdatetime datetime=(select getdate())
declare @csd_batdeg nvarchar(2000)
BEGIN
set @csd_batdeg='insert jkzx.'+@d_db+'.dbo.csd_batdeg'+' select * from '+@s_db+'.dbo.csd_batdeg where tm_datetime between dateadd(hour,'+convert(varchar(10),-@exec_time-24)+','+@paramtdatetime+') and dateadd(hour,'+convert(varchar(10),-@exec_time)+','+@paramtdatetime+')'
exec sp_executesql @csd_batdeg,@s_db,@d_db,@exec_time

如上

------解决方案--------------------
SQL code

ALTER PROCEDURE [dbo].[output_jkzx]
    @s_db nvarchar(100),
    @d_db nvarchar(100),
    @exec_time int
AS
declare @paramtdatetime datetime
set @paramtdatetime=getdate()
declare @csd_batdeg nvarchar(2000)
set @csd_batdeg='insert jkzx.'+@d_db+'.dbo.csd_batdeg'+
' select * from '+@s_db+
'.dbo.csd_batdeg where tm_datetime between dateadd(hour,'+
convert(varchar(10),-@exec_time-24)+','
+convert(varchar(10),@paramtdatetime,120)
+') and dateadd(hour,'+convert(varchar(10),-@exec_time)+
','+convert(varchar(10),@paramtdatetime,120)+')'
exec sp_executesql @csd_batdeg,@s_db,@d_db,@exec_time