1

I have an IF NOT EXISTS statement. IF it doesn't exist an INSERT statement follows. IF EXISTS I need to understand what is/can be returned so that I can interpret it with PHP.

so:

IF NOT EXISTS (SELECT id FROM users WHERE lname='SMITH') INSERT INTO users (lname='SMITH') 

I thought that the negative would return no result so could use a standard

if ($result){echo "record added";} else {echo "duplicate - no record added";} 

But that's not what's happening and I'm not sure how to achieve what I need - any suggestions?

Thank you for your kind attention.

1
  • How is $result being defined? SQL is still going to generate an 'I did something' object, although I'm not entirely sure what that looks like in PHP. To my knowledge, if no row is inserted, you'll get a (fairly) standard code 100; however, I'm not sure what the way you've written the SQL is going to do to that. I'd prefer re-writing it into a form which will always execute the INSERT, but it won't always have a row to do so. Commented Apr 24, 2012 at 20:34

2 Answers 2

1

In both cases $result would return the response for a successfully run command and nothing more. INSERT doesn't yield any rows, and neither does an IF statement that doesn't have a matching condition.

You can use SELECT SCOPE_IDENTITY() if you want to retrieve the inserted ID, and then you can check if $result has returned a row.

Sign up to request clarification or add additional context in comments.

4 Comments

I tried SELECT SCOPE_IDENTITY first but unfortunately it returns a result regardless - it's just the LAST result so this turns out to always be affirmative. Thank you for the input, PinnyM!
Right, but the idea was to perform the SELECT as part of the IF NOT EXISTS body, similar to @nonnb's solution
You're right, PinnyM...I can just use SELECT SCOPE_IDENTITY() before END and leave off the ELSE entirely. Better solution. Cheers!
It's also necessary to rewrite the php a bit: instead of if ($result) it needs to be if (mssql_fetch_array($result)) (this was required for both solutions)
1

You might try something like:

SET NOCOUNT ON IF NOT EXISTS (SELECT id FROM users WHERE lname='SMITH') BEGIN INSERT INTO users (lname) VALUES('SMITH') SELECT 1 END ELSE SELECT 0 

And check the returned scalar = 0 or 1 ?

1 Comment

I've ended up using a variation of what you've proposed: ...SELECT 1 AS response END ELSE SELECT NULL AS response which works...will have to do some more research on this when I have more time. Thanks for the response, nonnb!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.