复制 table 并放下

copy table and drop it

我知道我们可以简单地创建一个新的 table 并通过

复制旧的 table
select * into tbl2 from tbl1

我想检查 table tbl2 是否存在,如果存在则复制所有行,如果不存在则创建一个新行而不必在 tbl2 中指定列名,因为我' m 将 tbl2 中的所有列复制到 tbl1 中。然后,我想放弃旧的 table(tbl1)

if not exists(select * from tbl1 where id = 1)
   create table tbl2()
   drop tbl1
go
If object_id ("tempdb..#tbl2") is null
    Select * into #tbl2 from tbl1
Else
    Insert #tbl2 select * from tbl1

如果你不希望它成为临时文件 table 去掉 # 和 tempdb

这将检查tbl2,如果它存在,插入到table 2。如果它不存在,它会select到tbl2。

IF (EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                 WHERE TABLE_SCHEMA = 'schema' 
                 AND  TABLE_NAME = 'tbl2'))
BEGIN
    -- If the table exists, insert into:
    INSERT INTO tbl2 SELECT * from tbl1
    drop tbl1
END
ELSE
BEGIN
    SELECT * INTO tbl2 FROM tbl1
END

问题是,如果它确实存在,你怎么能确定 table 定义是完全相同的,如果你不想要这样的额外检查并始终假设它们是相同的,那么你可以使用 INSERT INTO ... SELECT * FROM

IF  NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[tbl2]') AND type in (N'U'))
BEGIN
    -- create the table only if not there
    select * into tbl2 from tbl1 where 1 <> 1
END

insert into tbl2 select * from tbl1

或者您可以将其更改为删除 1<>1 以仅插入记录,并将插入放入 else 块中。

IF  NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[tbl2]') AND type in (N'U'))
BEGIN
    -- create the table only if not there
    select * into tbl2 from tbl1
END
ELSE BEGIN
    insert into tbl2 select * from tbl1
END

存在的代码块是Sql Server management studio 生成的,我刚刚复制了它。

IF (EXISTS (SELECT * 
         FROM INFORMATION_SCHEMA.TABLES 
         WHERE TABLE_NAME = 'tbl2'))
BEGIN
    -- tbl2 exists, so just copy rows
    INSERT INTO tbl2 SELECT * FROM tbl1;
END
ELSE BEGIN
    -- tbl2 doesn't exist, so create new table tbl2 and copy rows 
    SELECT * INTO tbl2 FROM tbl1;
    DROP tbl1;
END

虽然这不会复制索引、键等 - 只是创建时的列名(在 else 分支中)。