views:

61

answers:

2

I'm trying to write a stored procedure that will create a new FILEGROUP based upon a given date parameter. What I want to see is a FILEGROUP called something like '2010_02_01'. What I get is a FILEGROUP called '@PartitionName'.

ALTER PROCEDURE [dbo].[SP_CREATE_DATE_FILEGROUP] @PartitionDate DATETIME
AS
DECLARE
    @PartitionName VARCHAR(10);
BEGIN
    SET @PartitionName = REPLACE(LEFT(CONVERT(VARCHAR, @PartitionDate, 120), 10), '-', '_');
    ALTER DATABASE MSPLocation ADD FILEGROUP [@PartitionName];
END
+1  A: 

You are going to end up having to using sp_executesql to execute it, something like

declare @sql nvarchar(4000)
setl @sql = 'ALTER DATABASE MSPLocation ADD FILEGROUP[' + @PartitionName + ']'
exec sp_executesql @sql
Andrew
We've taken your advice and settled upon an alternative to creating them on the fly but thanks for this answer too.
James Watt
Have a read of http://sqlfascination.com/2009/10/15/guidance-on-how-to-layout-a-partitioned-table-across-filegroups/ for some guidance / ideas.
Andrew
A: 

Use dynamic SQL:

DECLARE @FileGroupName sysname
SET @FileGroupName = 'Foo'

EXEC ('ALTER DATABASE MyDatabase ADD FILEGROUP [' + @FileGroupName + ']')

Think about SQL injection, though.

AakashM
The parameter is coming in declared a datetime, so injection is not going to occur.
Andrew