SQL/MySQL/Procedure Function/Set — различия между версиями

Материал из SQL эксперт
Перейти к: навигация, поиск
м (1 версия)
 
(нет различий)

Текущая версия на 10:17, 26 мая 2010

Assign value to a variable with set command

 
mysql>
mysql>
mysql> delimiter $$
mysql> CREATE PROCEDURE myProc()
    -> BEGIN
    ->     DECLARE my_integer     INT;           /* 32-bit integer */
    ->
    ->     set my_integer = 12;
    ->
    ->     select "my_integer = " + 12;
    -> END$$
Query OK, 0 rows affected (0.00 sec)
mysql> delimiter ;
mysql>
mysql> call myProc();
+----------------------+
| "my_integer = " + 12 |
+----------------------+
|                   12 |
+----------------------+
1 row in set (0.00 sec)
Query OK, 0 rows affected, 1 warning (0.00 sec)
mysql>
mysql> drop procedure myProc;
Query OK, 0 rows affected (0.00 sec)
mysql>
mysql>



Concatenate string with integer

 
mysql>
mysql> delimiter $$
mysql> CREATE PROCEDURE myProc()
    -> BEGIN
    ->
    ->   DECLARE a INT;
    ->   DECLARE b VARCHAR(20);
    ->   DECLARE c INT;
    ->
    ->   SET a=99;
    ->   SET b="AAA";
    ->   SET c=CONCAT(a," ",b);
    ->   SELECT c;
    -> END$$
Query OK, 0 rows affected (0.00 sec)
mysql>
mysql> delimiter ;
mysql>
mysql> call myProc();
+------+
| c    |
+------+
|   99 |
+------+
1 row in set (0.00 sec)
Query OK, 0 rows affected, 1 warning (0.00 sec)
mysql>
mysql> drop procedure myProc;
Query OK, 0 rows affected (0.00 sec)
mysql>
mysql>



Math operators

 
mysql>
mysql> delimiter $$
mysql>
mysql> CREATE PROCEDURE myProc()
    -> BEGIN
    ->         DECLARE a INT DEFAULT 2;
    ->         DECLARE b INT DEFAULT 3;
    ->         DECLARE c FLOAT;
    ->
    ->         SET c=a+b; SELECT "a+b=",c;
    ->         SET c=a/b; SELECT "a/b=",c;
    ->         SET c=a*b; SELECT "a*b=",c;
    ->
    -> END$$
Query OK, 0 rows affected (0.00 sec)
mysql>
mysql> delimiter ;
mysql>
mysql> call myProc();
+------+------+
| a+b= | c    |
+------+------+
| a+b= |    5 |
+------+------+
1 row in set (0.00 sec)
+------+----------+
| a/b= | c        |
+------+----------+
| a/b= | 0.666667 |
+------+----------+
1 row in set (0.02 sec)
+------+------+
| a*b= | c    |
+------+------+
| a*b= |    6 |
+------+------+
1 row in set (0.02 sec)
Query OK, 0 rows affected (0.02 sec)
mysql>
mysql> drop procedure myProc;
Query OK, 0 rows affected (0.00 sec)
mysql>
mysql>



Using Set to declare variable in a procedure

 
mysql>
mysql> delimiter $$
mysql>
mysql> CREATE PROCEDURE execute_immediate(in_sql varchar(4000))
    -> BEGIN
    ->
    ->   SET @tmp_sql=in_sql;
    ->   PREPARE s1 FROM @tmp_sql;
    ->   EXECUTE s1;
    ->   DEALLOCATE PREPARE s1;
    ->
    -> END$$
Query OK, 0 rows affected (0.00 sec)
mysql>
mysql> delimiter ;
mysql> call execute_immediate("select 1+1");
+-----+
| 1+1 |
+-----+
|   2 |
+-----+
1 row in set (0.00 sec)
Query OK, 0 rows affected (0.02 sec)
mysql> drop procedure execute_immediate;
Query OK, 0 rows affected (0.00 sec)