通过动态SQL语句创建游标

DECLARE @sql varchar(100);
DECLARE @TableName varchar(32);
DECLARE @FieldName varchar(32);
DECLARE @PrimaryKey varchar(32);
DECLARE @DbValue varchar(32);
DECLARE @PKey int;

--赋值
set @TableName='Student';
SET @FieldName='Name';
SET @PrimaryKey='Id';
--创建动态游标
set @sql = 'declare rowCursor cursor For select '+@PrimaryKey+' as PKey , '+@FieldName
+' as DbValue from '+@TableName;
EXEC(@sql);  
--打开游标
OPEN rowCursor; 
--取值
fetch next from rowCursor into @PKey,@DbValue;
--循环
while(@@FETCH_STATUS=0)
	begin
		declare @ExecSql varchar(100);
		set @ExecSql='Update '+@TableName +' set '+@FieldName+' = 234324324';
		PRINT @ExecSql
		EXEC(@ExecSql)
		fetch next from rowCursor into @PKey,@DbValue;
	end 
--关闭游标
close rowCursor;
--释放游标控件
deallocate rowCursor;

  

posted @ 2019-01-23 15:25  .NET开发菜鸟  阅读(630)  评论(0编辑  收藏  举报