简体   繁体   中英

Can I use the result of a select statement from mysql to compare it with a variable?

I have the following code in the my stored procedure:

SET cont_email = SELECT email from contacts  WHERE id=in_id;

IF in_customer_email = cust_email then

**do something**

So, I was wondering if instead of creating a local variable and storing the result from the SELECT statement I just paste it directly in the if statement like so:

IF in_customer_email = (SELECT email from contacts  WHERE id=in_id) then

    **do something**

Also, I was wondering how I can use ORs in MySQL.

Can I do this?

IF in_customer_email = customer_email OR in_customer_name = customer_name THEN

I have seen the use of OR like this:

SELECT customer_id, customer_name
FROM customers
WHERE (customer_name = 'Apple' OR customer_name = 'Samsung')

but never inside of an if statement, so I wasn't sure.

And lastly, it has been ages since I could use something like if var1 = var2 , since this is usually used for assigning not to compare, so I was wondering if this correct or I have to use double equal sign like var1 == var2 .

Thanks.

Variable vs. Nested Statement?

IF in_customer_email = (SELECT email from contacts  WHERE id=in_id) then

**do something**

This is a perfectly legal query -- no need to declare the variable beforehand.

ORs in IF Statements?

IF in_customer_email = customer_email OR in_customer_name = customer_name THEN

This is also perfectly legal (and often quite useful).

Use = or == to Compare Values?

if var1 = var2

This is, contrary to what your programmer spidey-sense may indicate, the proper way to compare values in MySQL queries.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM