MySQL: Insert a row and get the content?

MySQLMySQLi Database

In order to do insert a row and get the content, you need to use stored procedure, First, you need to create a table. After that you need to create a stored procedure that will insert a row and get the content to the end user.

To do the above task, let us first create a table. The query to create a table is as follows:

mysql> create table InsertRecord_SelectTable
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> Name varchar(20),
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (1.45 sec)

Now create a stored procedure that inserts a record in the above table and get back the result from the table immediately after calling the stored procedure. The query to create a stored procedure is as follows:

mysql> DELIMITER //
mysql> create procedure Insert_select
   -> (
   -> In tempName varchar(40)
   -> )
   -> begin
   -> declare tempId int unsigned;
   -> insert into InsertRecord_SelectTable(Name) values (tempName);
   -> set tempId = last_insert_id();
   -> select *from InsertRecord_SelectTable where Id= tempId;
   -> END //
Query OK, 0 rows affected (0.21 sec)
mysql> DELIMITER ;

Call the stored procedure to view, insert a row and get the content. The query to call stored procedure is as follows:

CALL yourStoredProcedureName;

Now you can call your stored procedure:

mysql> call Insert_select('John');

The following is the output:

+----+------+
| Id | Name |
+----+------+
| 1  | John |
+----+------+
1 row in set (0.12 sec)
Query OK, 0 rows affected, 1 warning (0.13 sec)
raja
Published on 26-Feb-2019 12:18:43
Advertisements