sqlite INSERT INTO … WHERE NOT EXISTS and get the id?

孤人 提交于 2019-12-10 21:51:57

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!