Question

I was wondering if syntax exist to express something like the following:

DECLARE @MyTableNameVARCHAR(50)
SET @MyTableName= 'AccountSummary'

CREATE TABLE dbo.@MyTableName
(
    Id int NOT NULL IDENTITY(1,1),
    AccountId int NOT NULL
    Amount real
)

Obviously, the above is not working. I made my scripts working with EXEC, but it seems rather convoluted. Can I use CREATE TABLE with a parameter for the tablename?

Était-ce utile?

La solution

DECLARE @MyTableName NVARCHAR(50);
SET     @MyTableName = 'AccountSummary';

DECLARE @Sql NVARCHAR(MAX);

SET @Sql =  N'CREATE TABLE '+ QUOTENAME(@MyTableName) + N'
            (
                Id int NOT NULL IDENTITY(1,1),
                AccountId int NOT NULL,
                Amount REAL
            )'

EXECUTE sp_executesql @Sql

OR

DECLARE @MyTableName NVARCHAR(50);
SET     @MyTableName = 'AccountSummary';

DECLARE @Sql NVARCHAR(MAX);

SET @Sql =  N'CREATE TABLE [@MyTableName]
            (
                Id int NOT NULL IDENTITY(1,1),
                AccountId int NOT NULL,
                Amount real
            )'

EXECUTE sp_executesql @Sql
                     ,N'@MyTableName NVARCHAR(50)'
                     ,@MyTableName

Autres conseils

"Can I use CREATE TABLE with a parameter for the tablename?"

No. You have to use dynamic SQL as you indicate you already have working.

This sort of thing is convoluted by nature.

Depending on what you are actually doing you might feel better about having a app layer constrcut the DDL, rather than doing it all in TSQL.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top