【问题标题】:insert into <x> select * from <y> results in error: Invalid object name '<y>'insert into <x> select * from <y> 导致错误:无效的对象名称'<y>'
【发布时间】:2017-08-27 18:33:25
【问题描述】:

Microsoft SQL Server 2016 (SP1) (KB3182545) - 13.0.4001.0 (X64) 28 2016 18:17:30 版权所有 (c) Microsoft Corporation Express Windows 10 Pro 6.3(内部版本 15063:)上的版本(64 位) (管理程序)

我创建一个全新的数据库,插入一些行,然后:

select * from table_1   
--> Query executed successfully, 50 rows

insert into table_2 select * from table_1   
--> Invalid object name 'table_2'

我做错了吗?

【问题讨论】:

  • 我们可以假设 table_2 存在并且名称是正确限定的吗?
  • 天哪,我真是个白痴:select * into table_2 from table_1
  • 这发生在我们所有人身上:-)

标签: sql-server


【解决方案1】:

SELECT INTO 仅在指定的表不存在时有效,因此在您的情况下,如果 _table_2_ 不存在,则:

SELECT * INTO table_2 FROM table_1; 

如果table_2存在,那么:

INSERT INTO table_2 SELECT (Col1, Col2, ..) FROM table_1;

【讨论】:

    【解决方案2】:

    我是个白痴。

    正确的语法是:

    select * into [table_2] from table_1 
    

    【讨论】:

    • 这是正确的,只要table_2尚不存在只是
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-09
    相关资源
    最近更新 更多