游标的格式:
DECLARE @usr_dy VARCHAR(5)
DECLARE MyCursor CURSOR FOR
SELECT DISTINCT USR_DY FROM TABLEA
Open MyCursor
Fetch Next From MyCursor into @usr_dy
While @@Fetch_Status = 0
begin
--游标处理部分
Fetch Next From MyCursor into @usr_dy
end
Close MyCursor
DeAllocate MyCursor
如果想在游标处理部分使用声明的标量来表示表格的字段名称,需要使用exec()函数,比如 :
exec('alter table #temptable4 add '+ @xy_cl +' int null ')
--SQL Server转义
SQL Server 如果需要对单引号进行转义,则写成‘’,比如:
exec(' select * from Table1 where usr_dy='''+ @usr_dy + ''' order by yymm ')