Jump to content

jnymris
 Share

Recommended Posts

Morning/Afternoon All, I'm trying to create a simple if statement in SQLThis has been casuing me so much trouble since yesterdayHere's what i'm trying to achieve.

IF((SELECT COUNT(*) FROM computers WHERE name='PC-01' AND domain='mydomain.local')==1)SELECT ComputerID FROM computers WHERE name='PC-01' AND domain='mydomain.local'ELSE IF((SELECT COUNT(*) FROM computers WHERE name='PC-01' AND domain='mydomain')==1)SELECT ComputerID FROM computers WHERE name='PC-01' AND domain='mydomain'ELSE IF(SELECT COUNT(*) FROM computers WHERE name='PC-01')==1)SELECT ComputerID FROM computers WHERE name='PC-01'

I have tried:

IF((SELECT COUNT(*) FROM computers WHERE name='PC-01' AND domain='mydomain.local')==1)BEGINSELECT ComputerID FROM computers WHERE name='PC-01' AND domain='mydomain.local'ENDELSE IF((SELECT COUNT(*) FROM computers WHERE name='PC-01' AND domain='mydomain')==1)BEGINSELECT ComputerID FROM computers WHERE name='PC-01' AND domain='mydomain'ENDELSE IF(SELECT COUNT(*) FROM computers WHERE name='PC-01')==1)BEGINSELECT ComputerID FROM computers WHERE name='PC-01'END

Along with other suggests which google returned. to no luck. How can a simple IF statement be so complicated? (Side Note: using phpmyadmin i cannot do print/echo/prompt commands is that normal?)

Link to comment
Share on other sites

I was never able to get them to work either (after considerable effort). I don't remember clearly why other than I was advised that sql doesn't work that way (or words to that effect). Consequently, I use WHERE in place of a simple if and php for more complicated ifs. I'll follow this topic in case a different approach is discussed /presented.

Edited by niche
Link to comment
Share on other sites

For MySQL, an if statement can only be used in stored functions, not regular queries. There is an if function that can be used in queries that is similar to the ternary operator in other languages. http://dev.mysql.com/doc/refman/5.5/en/control-flow-functions.html Other databases may support different features.

Link to comment
Share on other sites

For MySQL, an if statement can only be used in stored functions, not regular queries. There is an if function that can be used in queries that is similar to the ternary operator in other languages. http://dev.mysql.com...-functions.html Other databases may support different features.
Thanks justsomeguy How would I go about creating a function and then calling the function? I've never created a function in MySQL. any suggestions/tutorials?
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...