0

how to check the value exist before insert?

INSERT INTO DeliveryOrder (ContactName, ContactID) VALUES ('Andy', (SELECT ContactID FROM Contact WHERE ContactName = 'Andy')) 

I want to verify whether the ContactID is exist before insert the record.

Had try below but not working:

INSERT INTO DeliveryOrder (ContactName, ContactID) VALUES ('Andy', (SELECT ContactID FROM Contact WHERE ContactName = 'Andy')) WHERE IF Exists (SELECT ContactID FROM Contact WHERE ContactName = 'Andy')
2
  • 1
    You could check before hand (in a transaction), or you might find INSERT OR REPLACE or INSERT OR IGNORE to be useful (see SQLite docs). Commented May 4, 2017 at 9:45
  • Do not check for existence. Define a unique constrain and ignore constrain violation errors during import. Commented May 4, 2017 at 10:07

2 Answers 2

2
INSERT INTO DeliveryOrder (ContactName, ContactID)
 select 'Andy', ContactID
   from Contact
  WHERE ContactName = 'Andy'
Sign up to request clarification or add additional context in comments.

3 Comments

this woks better - it helps to think of your insert as recording your select - so if you write the select statement to return the values you need first then the Insert statement appears above it (with difficulties around sub queries)
but my contactname will be another fix value, then contactID will be take from a table.
@user14351 You can specify any values that are not in the table in the clause"select". Example updated.
0

This will help you

IF  EXISTS (SELECT ContactID
        FROM Contact  c
        WHERE
            c.ContactName ='Andy'
        )
Insert Into DeliveryOrder (ContactName, ContactID)
        VALUES ('Andy', (SELECT top 1 ContactID FROM Contact WHERE ContactName = 'Andy'))

Try this

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.