问题
is it possible to get the id even if I use INSERT INTO ... WHERE NOT EXISTS? how to modify it so it will bring me the id of the inserted record or the id of the already existed record? if possible at all!
INSERT INTO Timeline (name, ts)
SELECT @name, @ts
WHERE NOT EXISTS (SELECT 1 FROM Timeline WHERE name=@name AND ts = @ts);
i have a column called "id" with auto increment integer how I can get the value of the ID?
cheers
回答1:
You are guaranteeing that (name,ts)
is unique, so this should do the trick.
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
回答2:
you can use the output clause:
insert into Timeline output inserted.name
SELECT @name, @ts
WHERE NOT EXISTS (SELECT 1 FROM Timeline WHERE name=@name AND ts = @ts);
you can do it on the update too
update Timeline
set name = @name
output deleted.name as OLD_NAME, inserted.name as NEW_NAME
EDITED:
run this and you will understand:
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
来源:https://stackoverflow.com/questions/9212782/sqlite-insert-into-where-not-exists-and-get-the-id