eEcho blog

is een halte van de gedachte

SQL Variables in Queries

Probleem

U wilt een waarde bewaren om het later in de volgende query te kunnen gebruiken.

Oplossing

SQL variable bewaart de waarden voor het latere gebruik.

Voorbeeld

mysql> SELECT @id := cust_id FROM customers WHERE cust_id=’ customer name’;
mysql> DELETE FROM customers WHERE cust_id = @id;
mysql> DELETE FROM orders WHERE cust_id = @id;

mysql> SELECT @max_limbs := MAX(arms+legs) FROM limbs;

mysql> SELECT @last_id := LAST_INSERT_ID( );

mysql> SELECT @name := thing FROM limbs WHERE legs = 0;
+—————-+
| @name := thing |
+—————-+
| squid |
| octopus |
| fish |
| phonograph |
+—————-+
mysql> SELECT @name;
+————+
| @name |
+————+
| phonograph |

mysql> SELECT @name2 := thing FROM limbs WHERE legs < 0;
Empty set (0.00 sec)
mysql> SELECT @name2;
+——–+
| @name2 |
+——–+
| NULL |

mysql> SET @sum = 4 + 7;
mysql> SELECT @sum;
+——+
| @sum |
+——+
| 11 |

mysql> SET @x = 1; SELECT @x, @X;
+——+——+
| @x | @X |
+——+——+
| 1 | NULL |

mysql> SET @tbl_name = CONCAT(’tbl_’,FLOOR(RAND( )*1000000));
mysql> CREATE TABLE @tbl_name (int_col INT);
ERROR 1064 at line 2: You have an error in your SQL syntax near ‘@tbl_name
(int_col INT)’ at line 1

Add A Comment

You must be logged in to post a comment.

Home | info@eecho.info | Voorwaarden | Blog