0

I have to move some tables from primary file group to the default prime group. I have 3 different environments and in each environment name of the default file group is different. Thus, I can fetch the default file group name as:

select name from sys.filegroups where is_default=1;

Now while recreating my indexes I want to use the output of the above query to specify the file group where I want to create index(as default file group has different names in different environments, thus, I want only a single query to be promoted). I tried as:

CREATE UNIQUE CLUSTERED INDEX PK_INDEX
ON slam.MY_TABLE(COL_1)
WITH (DROP_EXISTING=ON) ON [select name from sys.filegroups where is_default=1];

But I am facing below error:

Msg 1921, Level 16, State 1, Line 19 Invalid filegroup 'select name from sys.filegroups where is_default=1' specified.

Any help will be much appreciated.

2
  • By default, any table or index you create will be stored in the default filegroup. You don't need to do anything special here - just remove the FG part. Commented Nov 29, 2018 at 13:09
  • The issue is a new filegroup has been created which has been marked as default..the tables and indexes were created before the creation of filegroup. I just want to shift the tables from PRIMARY file group to the newly created default file group Commented Nov 29, 2018 at 13:33

1 Answer 1

1

You need to use dynamic sql for that. Select the name of your default file group, construct your query and execute it like this:

declare @fg_name nvarchar(250), @sql nvarchar(max);
select @fg_name = name from sys.filegroups where is_default=1;
set @sql = N'CREATE UNIQUE CLUSTERED INDEX PK_INDEX
    ON slam.MY_TABLE(COL_1)
    WITH (DROP_EXISTING=ON) ON [' + @fg_name + N'];';
exec sp_executesql @sql;
Sign up to request clarification or add additional context in comments.

6 Comments

There is no way to do it in a single query?
I don't think so. You can combine constructing the query and selecting the file group name into single query, though. But why do you want to be a single query?
As I am not sure whether dynamic sql qill be allowed to me or not as per organizational standards
OK, then why not just omit the file group name. It should go to the default.
No it is not going
|

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.