0

I have no idea what I'm missing here:

IF (SELECT 'Nazwa' FROM stanowiska WHERE Nazwa LIKE = 'Lakiernik') IS NULL THEN  
INSERT INTO stanowiska (Nazwa) VALUES ('Lakiernik')
ELSE   
SELECT Nazwa FROM stanowiska WHERE Nazwa LIKE 'Lakiernik'

Any help would be appreciated

4
  • What are you trying to do? LIKE = isn't valid syntax, for instance. Commented Oct 24, 2015 at 15:34
  • Could you post your error message if any? Commented Oct 24, 2015 at 15:34
  • I want to check if the record exists. If no, I want to insert it. If yes, I just want to select it. Commented Oct 24, 2015 at 15:35
  • I have no idea what I'm missing here: - a question. Commented Oct 24, 2015 at 16:03

2 Answers 2

3

This might be what you want:

IF NOT EXISTS (SELECT 1 FROM stanowiska WHERE Nazwa = 'Lakiernik') THEN  
    INSERT INTO stanowiska (Nazwa)
        VALUES ('Lakiernik');
ELSE SELECT Nazwa FROM stanowiska WHERE Nazwa = 'Lakiernik'
END IF;

Even this is really strange. The code block is inserting in the THEN and return a value in the ELSE. That doesn't seem right. And, the part being returned is just Lakiernik, so I don't think the ELSE is needed:

IF NOT EXISTS (SELECT 1 FROM stanowiska WHERE Nazwa = 'Lakiernik') THEN  
    INSERT INTO stanowiska (Nazwa)
        VALUES ('Lakiernik');
END IF;

However, this has race conditions. So, if you want to prevent duplicates, the right way is:

create unique index unq_stanowiska_nazwa on stanowiska(nazwa);

Then:

    INSERT INTO stanowiska (Nazwa)
        VALUES ('Lakiernik')
        ON DUPLICATE KEY UPDATE nazwa = VALUES(Nazwa);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot for that answer. Works perfect
0

Try this, didn't test it yet:

IF (SELECT 1 FROM stanowiska WHERE Nazwa = 'Lakiernik') 
THEN  
INSERT INTO stanowiska (Nazwa) VALUES ('Lakiernik');
ELSE   
SELECT Nazwa FROM stanowiska WHERE Nazwa ='Lakiernik';
END IF;

1 Comment

it shows an error: #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IF (SELECT 1 FROM stanowiska WHERE Nazwa = 'Lakiernik') THEN INSERT INTO stan' at line 1

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.