在存储过程中将模式用作变量

时间:2018-11-28 03:03:34

标签: function variables stored-procedures schema

在存储过程中,我可以在表名前加上模式名。 例如: 从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 ;

0 个答案:

没有答案