在存储过程中,我可以在表名前加上模式名。 例如: 从SchemaName.CustomerTable中选择CustomerName
但是我想使用一个变量作为模式名称。
我有一个SP,该SP使用函数返回Schema的名称并将其分配给变量。 @RetVal
然后,我想使用该变量作为表名的前缀。 这是我尝试过的。
enter code here
CREATE DEFINER=`root`@`localhost` PROCEDURE `CustInfo`(Custcode varchar(255))
BEGIN
-- The following returns the schema name I want to use and stored in @RetVal
set @RetVal = GetCustDB(Custcode);
SELECT
strServerDB AS CustMySqlDB,
strCustName AS CustomerName,
strDemoUser AS DemoUser
FROM
@RetVal.tbl_200_010_CustomerInfo
WHERE
@RetVal.tbl_200_010_CustomerInfo.bolEnabled = 1 ;
解决方案:
DELIMITER $$
CREATE DEFINER='root'@'localhost' PROCEDURE CustInfo (Custcode varchar(255))
BEGIN
-- The following returns the schema name I want to use and stored in @RetVal
set @RetVal = GetCustDB(Custcode);
SET @s = CONCAT("SELECT strServerDB AS CustMySqlDB, strCustName AS
CustomerName, strDemoUser AS DemoUser FROM ", @RetVal,
".tbl_200_010_CustomerInfo WHERE ", @RetVal,
".tbl_200_010_CustomerInfo.bolEnabled = 1 ;");
PREPARE stmt1 FROM @s;
EXECUTE stmt1;
DEALLOCATE PREPARE stmt1;
END $$
DELIMITER ;