27,579
社区成员
发帖
与我相关
我的任务
分享
DECLARE @sql varchar(2000),@id varchar(2000) --申明变量
--申明一个游标
DECLARE authors_cursor CURSOR FOR
select tablename,PropertyName from EntityTable
--打开游标
OPEN authors_cursor
--取出值
FETCH NEXT FROM authors_cursor INTO @sql ,@id
--循环取出游标的值
WHILE @@FETCH_STATUS = 0
BEGIN
------------ 第二层
DECLARE @sql2 varchar(2000) --申明变量
--申明一个游标
DECLARE authors_cursor2 CURSOR FOR
exec('select ' +@id +' as id from '+ @sql)
--打开游标
OPEN authors_cursor2
--取出值
FETCH NEXT FROM authors_cursor INTO @sql2
--循环取出游标的值
WHILE @@FETCH_STATUS = 0
BEGIN
exec pwf_Del @sql2
FETCH NEXT FROM authors_cursor2
INTO @sql2
END
CLOSE authors_cursor2 --关闭游标
DEALLOCATE authors_cursor2 --释放游标
--------------
FETCH NEXT FROM authors_cursor
INTO @sql,@id
END
CLOSE authors_cursor --关闭游标
DEALLOCATE authors_cursor --释放游标
DECLARE @sql2 varchar(2000) --申明变量
--申明一个游标
DECLARE authors_cursor2 CURSOR FOR
exec('select ' +@id +' as id from '+ @sql)
--打开游标
OPEN authors_cursor2
--取出值
FETCH NEXT FROM authors_cursor INTO @sql2
--循环取出游标的值
WHILE @@FETCH_STATUS = 0
BEGIN
exec pwf_Del @sql2
FETCH NEXT FROM authors_cursor2
INTO @sql2
END
CLOSE authors_cursor2 --关闭游标
DEALLOCATE authors_cursor2 --释放游标
把上面这一段内容改成下面这样
DECLARE @authors_cursor2 VARCHAR(max) --最上面定义一个变量(把执行游标2的所有字符都拼接到里面)
SET @authors_cursor2=
N'DECLARE @sql2 varchar(2000) '+
N'DECLARE authors_cursor2 CURSOR FOR '+
N'select ' +@id +' as id from '+ @sql+
N' OPEN authors_cursor2'+
N'FETCH NEXT FROM authors_cursor INTO @sql2 '+
N'WHILE @@FETCH_STATUS = 0 '+
N'BEGIN '+
N'exec pwf_Del @sql2 '+
N'FETCH NEXT FROM authors_cursor2 '+
N'INTO @sql2 '+
N'END '+
N'CLOSE authors_cursor2 '+
N'DEALLOCATE authors_cursor2 '
PRINT @authors_cursor2
EXEC (@authors_cursor2)
这样试试看行不行
DECLARE @authors_cursor2 VARCHAR(max) --最上面定义一个变量(把执行游标2的所有字符都拼接到里面)
SET @authors_cursor2=
N'DECLARE @sql2 varchar(2000) '+
N'DECLARE authors_cursor2 CURSOR FOR '+
N'select ' +@id +' as id from '+ @sql+
N' OPEN authors_cursor2'+
N'FETCH NEXT FROM authors_cursor2 INTO @sql2 '+
N'WHILE @@FETCH_STATUS = 0 '+
N'BEGIN '+
N'exec pwf_Del @sql2 '+
N'FETCH NEXT FROM authors_cursor2 '+
N'INTO @sql2 '+
N'END '+
N'CLOSE authors_cursor2 '+
N'DEALLOCATE authors_cursor2 '
PRINT @authors_cursor2
EXEC (@authors_cursor2)
DECLARE @sql2 varchar(2000)
DECLARE authors_cursor2 CURSOR FOR
select ID as id from DFN_ZTH_FBS
OPEN authors_cursor2
FETCH NEXT FROM authors_cursor INTO @sql2
WHILE @@FETCH_STATUS = 0
BEGIN
exec pwf_Del @sql2
FETCH NEXT FROM authors_cursor2
INTO @sql2
END
CLOSE authors_cursor2
DEALLOCATE authors_cursor2
会提示这个。 每一句都提示
消息 16924,级别 16,状态 1,第 1 行
Cursorfetch: INTO 列表中声明的变量数目必须与所选列的数目相同。
CREATE TABLE #temp ( id INT )
INSERT INTO #temp
EXEC ( 'select ' + @id + ' as id from ' + @sql
)
DECLARE authors_cursor2 CURSOR
FOR
SELECT *
FROM #temp
DROP TABLE #temp