SQL SERVER中如何在声明游标的语句中,用变量做表名

时间:2023-03-08 16:39:23

-- 因为定义游标所用的表名是变量,所以采用EXEC(定义语句) 的方式来声明游标
set @StrSql='DECLARE Ba_Cursor CURSOR FOR (SELECT a.PhoneId from '+@TABLE+' a left JOIN tj_machine_log b on a.PhoneId=b.PhoneId where a.CreateTime BETWEEN '''+CONVERT(varchar(100), @STARTTIME, 20)+''' AND '''+CONVERT(varchar(100), @ENDTIME, 20)+''' AND b.PhoneId IS NULL GROUP BY a.PhoneId)'
--print @StrSql
exec(@StrSql)

            --记录铭心