Wednesday, April 20, 2011

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

I have a One Field Table in SQL CE which I need a SQL Statement for. The objective is to Delete the record if it already exists and insert the record if it does not exist. Is the possible with SQL CE?

INSERT INTO Source_Table
SELECT     'myvalue' AS Expr1
WHERE     (NOT EXISTS
                 (SELECT     Source_Data
                 FROM        Source_Table AS Source_Table_1
                 WHERE     (Source_Data = 'myvalue')))
From stackoverflow
  • Why not just...

    DELETE Source_Table WHERE Source_Data = 'myvalue'
    GO
    INSERT INTO Source_Table (Source_Data) values('myvalue')
    

    I'm not sure what the point of deleting a record and then inserting the same data would be, but this should accomplish it.

    jalf : One answer might be that SQL CE doesn't support batched queries. Becomes a bit of a pain if you have to perform two separate queries just for this.
    Adam Robinson : That SQL executes fine for me in SQL CE 3.5sp1. Did you see different results?
  • If the aim is to literally delete if it exists and only insert it if it does not exist, then you need to do what you've written.

    If the aim is to insert if it doesn't exist and replace if it does, Adam's correct that you may as well just always run the delete followed by the insert. I'd run both in the same statement batch, to save overhead.

    Were there more than one field, of course you'd do an update, not a delete followed by insert. (But delete followed by insert is how Sybase internally performs updates.)

0 comments:

Post a Comment