Show a MySQL user-defined variables values in the result table?

MySQLMySQLi Database

Use @ for variable and concat_ws() to display concatenated result in the table. Let us first create a table −

mysql> create table DemoTable1508
   -> (
   -> StudentFirstName varchar(20),
   -> StudentLastName varchar(20)
   -> );
Query OK, 0 rows affected (0.55 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1508 values('Chris','Brown');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable1508 values('David','Miller');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable1508 values('John','Doe');
Query OK, 1 row affected (0.15 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1508;

This will produce the following output −

+------------------+-----------------+
| StudentFirstName | StudentLastName |
+------------------+-----------------+
| Chris            |           Brown |
| David            |          Miller |
| John             |             Doe |
+------------------+-----------------+
3 rows in set (0.00 sec)

Here is the query to show a MySQL variable in the result table −

mysql> select @FullName:=concat_ws('-',StudentFirstName,StudentLastName) from DemoTable1508;

This will produce the following output −

+------------------------------------------------------------+
| @FullName:=concat_ws('-',StudentFirstName,StudentLastName) |
+------------------------------------------------------------+
| Chris-Brown                                                |
| David-Miller                                               |
| John-Doe                                                   |
+------------------------------------------------------------+
3 rows in set (0.03 sec)
raja
Published on 11-Dec-2019 10:37:08
Advertisements