[编辑]
根据 Mitch Wheat 的建议,插入现在可以使用(SCOPE_IDENTITY(), 'Semi-Fail')
, (@@IDENTITY, 'Semi-Fail')
; 但是,两者都在选择时产生NULL
值:
create clustered index test2_inx ON test2 (test1_id);
以下INSERT
s 都产生 NULL
INSERT INTO test1 VALUES ('Semi-failure');
INSERT INTO test2 VALUES (SCOPE_IDENTITY(), 'Semi-failure');
INSERT INTO test1 VALUES ('Semi-failure');
INSERT INTO test2 VALUES (@@IDENTITY, 'Semi-failure');
SELECT * FROM test2;
但是,使用IDENT_CURRENT
确实有效:
INSERT INTO test1 VALUES ('Success');
INSERT INTO test2 VALUES (IDENT_CURRENT('test1'), 'Success');
...但为什么我不能让它与其他两个一起工作?
谢谢你。
顺便说一句:来自 Oracle,表可以被创建为堆表以外的任何东西而不被指定为这样的概念,嗯,是疯狂的。那是云的事吗?有谁知道这样做的目的?
[/编辑]
DDL:
CREATE TABLE test1 (
id int identity(1,1)
,value varchar(20)
,CONSTRAINT test1_id_pk PRIMARY KEY (id)
);
CREATE TABLE test2 (
id int
,value varchar(20)
,CONSTRAINT test2_id_fk FOREIGN KEY (id) REFERENCES test1 (id)
)
插入 test1 语句:
INSERT INTO test1 VALUES ('failure');
以下所有失败并出现相同的错误:
INSERT INTO test2 VALUES (SCOPE_IDENTITY(), 'fail');
INSERT INTO test2 VALUES (select SCOPE_IDENTITY(), 'fail');
INSERT INTO test2 VALUES ( (select SCOPE_IDENTITY()) , 'fail');
INSERT INTO test2 VALUES (@@IDENTITY, 'fail');
INSERT INTO test2 VALUES (select @@IDENTITY, 'fail');
INSERT INTO test2 VALUES ( (select @@IDENTITY), 'fail');
INSERT INTO test2 VALUES (IDENT_CURRENT('test1'), 'fail');
INSERT INTO test2 VALUES (select IDENT_CURRENT('test1'), 'fail');
INSERT INTO test2 VALUES ( (select IDENT_CURRENT('test1'), 'fail');
对于上述每个INSERT
语句,我收到以下错误之一:
Tables without a clustered index are not supported in this version of SQL Server. Please create a clustered index and try again.
Incorrect syntax near the keyword 'select'.
此外,以下 select 语句在INSERT
进入 test1 之后返回 null:
SELECT SCOPE_IDENTITY();
SELECT @@IDENTITY;
而以下返回正确的值:
SELECT IDENT_CURRENT('test1');