Вопрос

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