首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

还是动态SQL的有关问题,“必须声明标量变量”

2012-09-24 
还是动态SQL的问题,“必须声明标量变量”?--赋值当前时间declare @endtime datetimedeclare @begintime date

还是动态SQL的问题,“必须声明标量变量”?

--赋值当前时间
declare @endtime datetime
declare @begintime datetime
declare @year nvarchar(4)
declare @ln nvarchar(1000)
declare @str nvarchar(1000)

select @endtime=getdate()
  ,@begintime=dateadd(dd,-120,getdate())
  ,@year=year(getdate())
--统计目标表中LN站特定时间的记录总数
declare @select2 int
--统计LN表中特定时间的记录总数
set @str='SELECT count(*)
  FROM openrowset(''SQLOLEDB'',''172.19.18.133'';''sa'';''sa'',Meso_'+@year+'.dbo.LN_'+@year+' ) 
where DATEPART(minute, cast(观测时间 as dateTime))=0 and @begintime<观测时间 and 观测时间<@endtime '
exec(@str)
---------------------------
消息 137,级别 15,状态 2,第 3 行
必须声明标量变量 "@begintime"。
------------------------
动态SQL,有些问题还是弄不太清楚。


[解决办法]
动态执行要把datetime转成字符串.
set @str='SELECT count(*) 
FROM openrowset(''SQLOLEDB'',''172.19.18.133'';''sa'';''sa'',Meso_'+@year+'.dbo.LN_'+@year+' ) 
where DATEPART(minute, cast(观测时间 as dateTime))=0 and '+@begintime+' <观测时间 and 观测时间 <'+@endtime 

改为:
set @str='SELECT count(*) 
FROM openrowset(''SQLOLEDB'',''172.19.18.133'';''sa'';''sa'',Meso_'+@year+'.dbo.LN_'+@year+' ) 
where DATEPART(minute, cast(观测时间 as dateTime))=0 and '''+convert(varhcar(30),@begintime)+''' <观测时间 and 观测时间 <'+convert(varchar(30),@endtime)+''''; 

热点排行
Bad Request.