我有一张带有标识栏的表说:
create table with_id ( id int identity(1,1),val varchar(30) );@H_301_4@众所周知,这一点
select * into copy_from_with_id_1 from with_id;@H_301_4@导致copy_from_with_id_1也带有id身份. @H_301_4@以下stack overflow question提及明确列出所有列. @H_301_4@我们试试吧
select id,val into copy_from_with_id_2 from with_id;@H_301_4@糟糕,即使在这种情况下,id也是一个标识列. @H_301_4@我想要的是像一张桌子
create table without_id ( id int,val varchar(30) );
解决方法
从
Books Online起
@H_301_4@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.@H_301_4@在页面下方:
@H_301_4@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:@H_301_4@那么……你理论上可以逃脱:@H_301_4@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.
- 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.
select id,val into copy_from_with_id_2 from with_id union all select 0,'test_row' where 1 = 0;@H_301_4@重要的是要对此代码进行评论以解释它,以免在下次有人看到它时将其删除.