sql-server – 如何使用SELECT INTO复制表但忽略IDENTITY属性?

前端之家收集整理的这篇文章主要介绍了sql-server – 如何使用SELECT INTO复制表但忽略IDENTITY属性?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一张带有标识栏的表说:
create table with_id (
 id int identity(1,1),val varchar(30)
);

众所周知,这一点

select * into copy_from_with_id_1 from with_id;

导致copy_from_with_id_1也带有id身份.

以下stack overflow question提及明确列出所有列.

我们试试吧

select id,val into copy_from_with_id_2 from with_id;

糟糕,即使在这种情况下,id也是一个标识列.

我想要的是像一张桌子

create table without_id (
 id int,val varchar(30)
);

解决方法

Books Online

The format of new_table is determined by evaluating the expressions in the select list. The columns in new_table are created in the order specified by the select list. Each column in new_table has the same name,data type,nullability,and value as the corresponding expression in the select list. The IDENTITY property of a column is transferred except under the conditions defined in “Working with Identity Columns” in the Remarks section.

页面下方:

When an existing identity column is selected into a new table,the new column inherits the IDENTITY property,unless one of the following conditions is true:

  • The SELECT statement contains a join,GROUP BY clause,or aggregate function.
  • Multiple SELECT statements are joined by using UNION.
  • The identity column is listed more than one time in the select list.
  • The identity column is part of an expression.
  • The identity column is from a remote data source.

If any one of these conditions is true,the column is created NOT NULL instead of inheriting the IDENTITY property. If an identity column is required in the new table but such a column is not available,or you want a seed or increment value that is different than the source identity column,define the column in the select list using the IDENTITY function. See “Creating an identity column using the IDENTITY function” in the Examples section below.

那么……你理论上可以逃脱:

select id,val 
into copy_from_with_id_2 
from with_id

union all

select 0,'test_row' 
where 1 = 0;

重要的是要对此代码进行评论以解释它,以免在下次有人看到它时将其删除.

原文链接:https://www.f2er.com/mssql/80074.html

猜你在找的MsSQL相关文章