简体   繁体   中英

How to use a variable to specify filegroup in SQL Server

I want to alter a table to add a constraint during upgrade on a SQL Server database.

This table is normally indexed on a filegroup called 'MY_INDEX' - but may also be on a database without this filegroup. In this case I want the indexing to be done on the 'PRIMARY' filegroup.

I tried the following code to achieve this:

DECLARE @fgName AS VARCHAR(10)

SET @fgName = CASE WHEN EXISTS(SELECT groupname
                                FROM sysfilegroups
                                WHERE groupname = 'MY_INDEX')
                    THEN QUOTENAME('MY_INDEX')
                    ELSE QUOTENAME('PRIMARY')
              END

ALTER TABLE [dbo].[mytable]
ADD CONSTRAINT [PK_mytable] PRIMARY KEY
(
    [myGuid] ASC
)
ON @fgName -- fails: 'incorrect syntax'

However, the last line fails as it appears a filegroup cannot be specified by variable.

Is this possible?

I've found that dynamic sql works when passing variables in DDL statements.

Try something like this:

DECLARE @fgName AS VARCHAR(10) 

SET @fgName = CASE WHEN EXISTS(SELECT groupname 
                                FROM sysfilegroups 
                                WHERE groupname = 'MY_INDEX') 
                    THEN QUOTENAME('MY_INDEX') 
                    ELSE QUOTENAME('PRIMARY') 
              END 

DECLARE @sql as varchar(1024)

SET @sql = 'ALTER TABLE [dbo].[mytable] ADD CONSTRAINT [PK_mytable] PRIMARY KEY ( 
    [myGuid] ASC ) ON ' + @fgName

EXEC(@sql)

I hope that helps....

I would believe that if SQL Server returns an incorrect syntax , there's probably no way to do this, unfortunately.

You will need to specify your filegroup names as string literals.

You will probably just have to rewrite your script to be something like:

IF EXISTS(SELECT groupname FROM sysfilegroups WHERE groupname = 'MY_INDEX')
     ALTER TABLE [dbo].[mytable]
       ADD CONSTRAINT [PK_mytable] 
       PRIMARY KEY([myGuid] ASC) ON 'MY_INDEX'
ELSE
     ALTER TABLE [dbo].[mytable]
       ADD CONSTRAINT [PK_mytable] 
       PRIMARY KEY([myGuid] ASC) ON 'PRIMARY'

ELSE QUOTENAME('[PRIMARY]')替换ELSE QUOTENAME('PRIMARY') ELSE QUOTENAME('[PRIMARY]')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM