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?

有帮助吗?

解决方案

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

其他提示

"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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top