嗨我想在从另一个表中插入表格时填充自动增量列的值。下面是查询即时使用,它抛出错误
create table test12
(
Id int,
name varchar(255),
dept varchar(255)
)
insert into test12 values(1,'f','cs'),(2,'b','cse'),(3,'c','cs'),(4,'d','cse'),(5,'e','cs'),(6,'f',null)
select * from test12
create table test34
(
seq int identity(1,1) not null,
name varchar(255) not null,
dept varchar(255) default('cs')
)
insert into test34(seq,name,dept) values
(1,(select name from test12),
(select case when dept='cse' then 'Y' else 'N' end as dept from test12))
请告诉我这是什么错误
答案 0 :(得分:3)
你不需要为Identity列赋值,它是自动添加的,只需将标识列表单插入为:
INSERT INTO test34 (name, dept)
SELECT
name,
CASE WHEN dept = 'cse' THEN 'Y' ELSE 'N' END AS dept
FROM test12
如果您确实想手动添加身份值,请尝试以下SET语句。
SET IDENTITY_INSERT test34 ON;
INSERT INTO test34 (seq, name, dept)
SELECT
ID
name,
CASE WHEN dept = 'cse' THEN 'Y' ELSE 'N' END AS dept
FROM test12
SET IDENTITY_INSERT test34 OFF;
答案 1 :(得分:1)
您可以转为ON
或OFF
IDENTITY_INSERT
SET IDENTITY_INSERT test34 ON
insert into test34(seq,name,dept) values
(1,(select name from test12),
(select case when dept='cse' then 'Y' else 'N' end as dept from test12))
SET IDENTITY_INSERT test34 OFF
答案 2 :(得分:-1)
无需自动为自动增量列插入值,它将生成值。
insert into test34(name,dept)
select name, Case when dept='cse' then 'Y' else 'N' end as dept from test12