即使我使用INSERT INTO而不是EXISTS,是否可以获取id? 如何修改它,这将带给我插入记录的ID或已存在的记录的ID?如果可能的话!
INSERT INTO Timeline (name, ts)
SELECT @name, @ts
WHERE NOT EXISTS (SELECT 1 FROM Timeline WHERE name=@name AND ts = @ts);
我有一个名为“ id ”的列,其中包含自动增量整数 我怎么能得到ID的价值?
欢呼声
答案 0 :(得分:1)
您保证(name,ts)
是唯一的,所以这应该可以解决问题。
INSERT INTO Timeline (name, ts)
SELECT @name, @ts
WHERE NOT EXISTS (SELECT 1 FROM Timeline WHERE name=@name AND ts = @ts);
SELECT id, name, ts from TimeLine
WHERE name=@name AND ts = @ts
答案 1 :(得分:-1)
你可以使用输出子句:
insert into Timeline output inserted.name
SELECT @name, @ts
WHERE NOT EXISTS (SELECT 1 FROM Timeline WHERE name=@name AND ts = @ts);
您也可以在更新中执行此操作
update Timeline
set name = @name
output deleted.name as OLD_NAME, inserted.name as NEW_NAME
编辑:
运行这个,你会理解:
create table Timeline(
id int not null primary key identity(1,1),
name varchar(50),
ts varchar(50))
insert into timeline output inserted.ID
values ('first record', 'ts')
--it will show 1
insert into Timeline output inserted.ID
SELECT 'first record', 'ts'
union select 'new record', 'ts'
WHERE NOT EXISTS (SELECT 1 FROM Timeline WHERE name='first record' AND ts = 'ts')
--ir will show 2 because the 1 already exits