Q

Syntax error in SQL Server script

I'm currently working on table partitioning. I'm struggling with using this " SELECT MAX(NAME) from sys.filegroups WHERE NAME NOT LIKE 'PRIMARY' " in order to get the last used Filegroup. Now this works just fine, but when I run the following script: --Decalre variables DECLARE @LastFilegroupName VARCHAR(50) DECLARE @FilegroupName VARCHAR(50) --Retuns the next FileGroup to be used SET @LastFilegroupName = (select MAX(NAME) from sys.filegroups WHERE NAME NOT LIKE 'PRIMARY') SET @LastFilegroupName = Replace(@LastFilegroupName,'FileGrp','') SET @FilegroupName = 'FileGrp' + CAST((@LastFilegroupName + 1) as varchar(10)) --Alter database statement ALTER DATABASE VadivelTesting ADD FILEGROUP @NewFG_Name This script gives the following error "Incorrect syntax near '@NewFG_Name'." When I give it a static name it works fine, but not with the variable. What should I do?

I'm currently working on table partitioning. I'm struggling with using this " SELECT MAX(NAME) from sys.filegroups WHERE NAME NOT LIKE 'PRIMARY' " in order to get the last used Filegroup. Now this works just fine, but when I run the following script: --Decalre variables DECLARE @LastFilegroupName VARCHAR(50) DECLARE @FilegroupName VARCHAR(50) --Retuns the next FileGroup to be used SET @LastFilegroupName = (select MAX(NAME) from sys.filegroups WHERE NAME NOT LIKE 'PRIMARY') SET @LastFilegroupName = Replace(@LastFilegroupName,'FileGrp','') SET @FilegroupName = 'FileGrp' + CAST((@LastFilegroupName + 1) as varchar(10)) --Alter database statement ALTER DATABASE VadivelTesting ADD FILEGROUP @NewFG_Name This script gives the following error "Incorrect syntax near '@NewFG_Name'." When I give it a static name it works fine, but not with the variable. What should I do?
I don't believe that the filegroup name can be a variable in the ALTER DATABASE statement. Try the following:

EXEC ('ALTER DATABASE VadivelTesting ADD FILEGROUP ' + @NewFG_Name)
This was last published in February 2007

PRO+

Content

Find more PRO+ content and other member only offers, here.

Have a question for an expert?

Please add a title for your question

Get answers from a TechTarget expert on whatever's puzzling you.

You will be able to add details on the next page.

Start the conversation

Send me notifications when other members comment.

By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

Please create a username to comment.

-ADS BY GOOGLE

SearchBusinessAnalytics

SearchDataCenter

SearchDataManagement

SearchAWS

SearchOracle

SearchContentManagement

SearchWindowsServer

Close