Using SQl Server CE; Possible to Insert Only If Not Exists?

拈花ヽ惹草 提交于 2020-02-15 04:20:49

问题


I'm trying to verify a simple 1 field table to determine if a record exists before inserting a duplicate.

if not exists (select * from url where url = ...)
insert into url...

Can someone Help?


回答1:


Your code example will run in the full version of SQL, or you could rearrange to the following:

insert into url
select 'myvalue'
where not exists (select * from url where url = 'myvalue')



回答2:


You might want to read this thread. performing-insert-or-update-upsert-on-sql-server-compact-edition

In a nutshell a sqlce specific solution (using SqlCeResultSet) will provide the maximum performance.




回答3:


Just reverse it and add the condition as a where clause predicate

 Insert Into Table .... 
  Where Not Exists 
 (Select * From table where ...) 

... But your basic problem sounds like it might be better solved by putting a alternate key (unique) constraint on the insert table, referencing the url column (I assume Sql CE does Referential Integrity (RI) constraints?)




回答4:


Use an Outer Join

Insert into X(...) select blah, blah, blah from table t left outer join X on t.id=x.id where x.id is null




回答5:


Granted, this is way past the posting date, but since I've not seen this answered elsewhere in my quick Google search, I thought I'd share how I solved this with SQL CE so others searching might find an answer.

-- Update existing record's value
UPDATE myTable
SET myValue = 'Hello World'
WHERE keyField = 'MyKey';

-- Insert new record if existing record doesn't exist`

INSERT INTO myTable (keyField, myValue)
SELECT I.keyField, I.myValue
FROM (
SELECT 'Hello World' AS myValue, 'MyKey' AS keyField
) I
LEFT JOIN myTable T ON I.keyField = T.keyField
WHERE T.keyField IS NULL;




回答6:


You are on the right path with IF NOT EXISTS. It is better to use IF NOT EXISTS() or IF EXISTS() than a Sub Query because SQL Server will stop scanning rows in the table when it finds the first instance that matches the EXISTS() condition your looking for. With a Sub Query written in the examples above it will scan the whole table.

A Classic example is the Insert or Update aka the SAVE.

IF EXISTS(SELECT * FROM Table_A WHERE Column_1 = @Parameter)
BEGIN
    --Update Statement here.
END
ELSE
BEGIN
    --Insert Statement here.
END



回答7:


What about something like this:

UPDATE Table1 SET (...) WHERE Column1='SomeValue'
IF @@ROWCOUNT=0
    INSERT INTO Table1 VALUES (...)

Source



来源:https://stackoverflow.com/questions/726448/using-sql-server-ce-possible-to-insert-only-if-not-exists

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