我正在尝试使用游标进行动态查询,我想为数据库中的每个表创建文件组,我有这个:
DECLARE @name VARCHAR(50)
DECLARE @query VARCHAR(50)
DECLARE vend_cursor CURSOR
FOR SELECT name FROM sys.tables order by name asc
OPEN vend_cursor
FETCH NEXT FROM vend_cursor;
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT 'FG_'+@name
FETCH NEXT FROM vend_cursor INTO @name;
END
CLOSE vend_cursor
DEALLOCATE vend_cursor
打印是因为我可以看到文件组名称将如何,但我想添加这个: ALTER DATABASE AdventureWorks2012 添加FILEGROUP FG_filegroupname
我知道我必须使用'exec sys.sp_executesql',但是如何将其添加到我的查询中呢?提前谢谢
答案 0 :(得分:2)
是的,您可以使用sp_executeSQL执行此操作,但最重要的是您需要设置GLOBAL游标,因为sp_executeSQL与您正在执行的过程不在同一范围内。见例子
DECLARE @SQL nvarchar(1024),
@name varchar(255);
SET @SQL = 'DECLARE vend_cursor CURSOR GLOBAL
FOR
SELECT name FROM sys.tables order by name asc';
EXECUTE sp_executesql @SQL;
OPEN vend_cursor
FETCH NEXT FROM vend_cursor INTO @name;
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT 'FG_'+@name
FETCH NEXT FROM vend_cursor INTO @name;
END
CLOSE vend_cursor
DEALLOCATE vend_cursor