I am trying to implement the below query in a stored procedure.
SELECT d.empno, d.fecthIdId, c.empno
FROM MyDatabase.myTable a
JOIN MyDatabase.myTable b ON a.id = b.xid
JOIN MyDatabase.Table2 c ON b.Id = cId
JOIN MyDatabase.Table3 d ON a.bid = d.cid AND d.empId = _empId
Stored Procedure:
DELIMITER $$
CREATE PROCEDURE `TestSP`(_empId INT, _myTable VARCHAR(50))
BEGIN
SET @mysql.SQL
= CONCAT('SELECT d.empno, d.fecthIdId, c.empno
FROM MyDatabase.',_myTable,' a
JOIN MyDatabase.',_myTable,' b ON a.id = b.xid
JOIN MyDatabase.Table2 c ON b.Id = cId
JOIN MyDatabase.Table3 d ON a.bid = d.cid AND d.empId = _empId');
PREPARE dynamicQuery FROM @mysql.SQL;
EXECUTE dynamicQuery;
DEALLOCATE PREPARE dynamicQuery;
END$$
DELIMITER ;
Procedure Call:
call TestSP(10, 'myTable');
Error:
Error Code: 1113. A table must have at least 1 column
I'm not sure what's wrong with the code. Thanks for your help.
You'd debug your code.
CREATE PROCEDURE `TestSP`(_empId INT, _myTable VARCHAR(50))
BEGIN
SET @mysql.SQL
= CONCAT('SELECT d.empno, d.fecthIdId, c.empno
FROM MyDatabase.',_myTable,' a
JOIN MyDatabase.',_myTable,' b ON a.id = b.xid
JOIN MyDatabase.Table2 c ON b.Id = cId
JOIN MyDatabase.Table3 d ON a.bid = d.cid AND d.empId = _empId');
/*
PREPARE dynamicQuery FROM @mysql.SQL;
EXECUTE dynamicQuery;
DEALLOCATE PREPARE dynamicQuery;
*/
SELECT @mysql.SQL `built SQL code`;
END
call TestSP(10, 'myTable');
built SQL code |
---|
SELECT d.empno, d.fecthIdId, c.empno FROM MyDatabase.myTable a JOIN MyDatabase.myTable b ON a.id = b.xid JOIN MyDatabase.Table2 c ON b.Id = cId JOIN MyDatabase.Table3 d ON a.bid = d.cid AND d.empId = _empId |
Now copypaste this code into your CLI and try to execute it.
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.