0

Is it possible to just create a table in MSSQL without columns?

I'm asking this because I'll have to check for every columns if it already exists or not.

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Tags]') AND type in (N'U'))
    BEGIN
        CREATE TABLE [dbo].Tags(
        [Id] [int] IDENTITY(1,1) NOT NULL,
         CONSTRAINT [PK_Tags] PRIMARY KEY CLUSTERED 
        (
            [Id] ASC
        )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
        ) ON [PRIMARY]
    END
GO

The execution might break by creating the column Id if the table and the column already exists.

This would be ideally:

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Tags]') AND type in (N'U'))
CREATE TABLE [dbo].Tags
GO

if NOT EXISTS (select column_name from INFORMATION_SCHEMA.columns where table_name = 'Tags' and column_name = 'Id')
  alter table MyTable add MyColumn int IDENTITY(1,1) NOT NULL
GO

-- add new primary key constraint on new column   
ALTER TABLE dbo.Tags 
ADD CONSTRAINT PK_Tags
PRIMARY KEY CLUSTERED ([Id] ASC)
GO

I can't find an example on the second piece of code. But I can imagine that a table can't be created with 0 columns.

Any suggestions?

[Edit] Some more context. Some tables exists some don't. Some columns exists some don't. I want to creat a script which could be executed anytime without breaking or causing error msg's like the table/column already exists.

4

3 回答 3

2

这段代码

create table tab

引发错误

'tab' 附近的语法不正确。

和这段代码

 create table tab1
 (
   id int
 )

 alter table tab1 drop id

引发错误

ALTER TABLE 'tab1' 失败。不允许删除表中的所有列。

所以没有列的表是不可能的。

于 2013-09-18T13:32:13.800 回答
0

当然你不能在 SQL Server 中创建没有列的表,但是如果表在你创建之前不存在,那么它就没有任何列,那你为什么不简单地创建它呢?

如果这是一种升级脚本,您可能会创建一个 ELSE 分支,在添加之前检查每一列。

于 2013-09-18T13:33:32.363 回答
0

我认为您可以使用以下方法实现您正在尝试的内容:

Id使用 ID 创建表,如果您不必创建表,则仅检查列是否存在。

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Tags]') AND type in (N'U'))
BEGIN 
    CREATE TABLE [dbo].Tags (Id int IDENTITY(1,1) NOT NULL)
END
ELSE
BEGIN
    if NOT EXISTS (select column_name from INFORMATION_SCHEMA.columns where table_name = 'Tags' and column_name = 'Id')
    BEGIN
        alter table [dbo].Tags add MyColumn int IDENTITY(1,1) NOT NULL

        -- add new primary key constraint on new column   
        ALTER TABLE dbo.Tags 
        ADD CONSTRAINT PK_Tags
        PRIMARY KEY CLUSTERED ([Id] ASC)
    END
ELSE

GO
于 2013-09-18T13:36:25.357 回答