How to: Use a variable in ALTER/CREATE PARTITION SCHEME command for filegroup?

  • Is it possible to use a variable to specify the filegroup in the ALTER/

    CREATE PARTITION SCHEME command?

    I want the partition scheme to use the default filegroup for ALTER and

    CREATE PARTITION SCHEME. At the time the script is created, I don't

    know the default filegroup in the database.

    My code:

    declare @fileGroupName VARCHAR(50) = (select top 1 name from

    sys.filegroups where is_default = 1)

    ALTER PARTITION SCHEME MyScheme NEXT USED @fileGroupName

    Is failing:

    Incorrect syntax near '@fileGroupName'.

    Q: Is it possible to use a variable for the filegroup in the ALTER/

    CREATE commands? Is so, what is the correct syntax?

    Q: If using a variable is not possible, is there another way to

    specify the default filegroup?

  • I'll answer my own question:

    Dynamic SQL.

    Instead of:

    declare @fileGroupName VARCHAR(50) = (select top 1 name from sys.filegroups where is_default = 1)

    ALTER PARTITION SCHEME MyScheme NEXT USED @fileGroupName

    Use:

    declare @fileGroupName VARCHAR(50) = (select top 1 name from sys.filegroups where is_default = 1)

    declare @sql VARCHAR(256) = 'ALTER PARTITION SCHEME MyScheme NEXT USED ' + @fileGroupName

    EXEC (@sql)

  • Thanks.

    This really help me.

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply