0

I'm trying to make a dynamic query, using a cursor, I wanna create filegroups to every tables on my database, I have this:

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

The print is because then I can see how the filegroup name will be, but I wanna add this: ALTER DATABASE AdventureWorks2012 ADD FILEGROUP FG_filegroupname

I know I have to use 'exec sys.sp_executesql', but how can I add this to my query? thanks in advance

1 Answer 1

5

Yes you can do this with sp_executeSQL but the most important thing is that you need to setup a GLOBAL cursor, because sp_executeSQL is not in the same scope as the procedure which you are executing. See example

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.