34,838
社区成员




create table ta(id int identity(1,1),a varchar(10),col1 int,col2 int)
create table tb(id int identity(1,1),a varchar(10),col1 int,col2 int)
go
insert into ta select 'w',1,2
insert into ta select 'w',1,2
insert into ta select 'w',1,2
insert into ta select 'w',1,2
insert into ta select 'w',1,2
insert into ta select 'w',1,2
declare @s varchar(2000)
select @s = isnull(@s+',','')+a.name
from syscolumns a
where id = object_id('ta')
and COLUMNPROPERTY( a.id,a.name,'IsIdentity') <> 1
order by colid
exec('insert tb select '+ @s+ ' from ta where a = ''w''')
select * from tb
/*
id a col1 col2
----------- ---------- ----------- -----------
1 w 1 2
2 w 1 2
3 w 1 2
4 w 1 2
5 w 1 2
6 w 1 2
(所影响的行数为 6 行)
*/
drop table ta,tb
--1. 会话中某个表已将此属性设置为ON,当为另一个表发出了SET IDENTITY_INSERT ON 句时将出错
--测试的表
CREATE TABLE ta(id int IDENTITY(1,1),col int)
CREATE TABLE tb(id int IDENTITY(1,1),col int)
GO
--设置 IDENTITY_INSERT 属性
SET IDENTITY_INSERT ta ON
SET IDENTITY_INSERT tb ON
GO
/*======================================================*/
--2. 如果插入记录的标识值大于表的当前标识值,则SQL Server自动将新插入值作为当前标识值使用
--测试的表
CREATE TABLE tb(id int IDENTITY(1,1),col int)
--强制在表中插入标识值
SET IDENTITY_INSERT tb ON
INSERT tb(id,col) VALUES(10,1)
SET IDENTITY_INSERT tb OFF
INSERT tb(col) VALUES(2)
SELECT * FROM tb
/*--结果
id col
----------------- -----------
10 1
11 2
--*/
GO
/*======================================================*/
--3. 如果插入记录的标识值小于表的当前标识值,则表的当前标识值不受新插入值的影响
--测试的表
CREATE TABLE tb(id int IDENTITY(1,1),col int)
INSERT tb VALUES(1)
INSERT tb VALUES(2)
--强制在表中插入标识值
SET IDENTITY_INSERT tb ON
INSERT tb(id,col) VALUES(1,11)
SET IDENTITY_INSERT tb OFF
INSERT tb(col) VALUES(3)
SELECT * FROM tb
/*--结果
id col
----------------- -----------
1 1
2 2
1 11
3 3
--*/