MySQL 动态设置数据库名称 select db.schematable

MySQL set database name dynamically and select db.schematable

我正在创建一个存储过程,它需要一些输入参数。我希望能够 select 使用哪个数据库,然后根据如下所示的条件,我想使用正确的 where 条件。

我知道你不能在存储过程中使用 "USE" 关键字,我也尝试在查询中设置 @ds 但没有成功。

我正在使用 Navicat 并在 IDE 中定义了我的参数,我的输入参数是:

SQL

BEGIN
declare dbName varchar(255); --attempt at using db name passed in
select imemberdbname into dbName;
set @ds = concat(dbName,'.customers'); -- I have also tried this

if LENGTH(icustomername) > 0 THEN
    (Select customerid, customername, postcode, accountnumber from dbName.customers
        WHERE customername = icustomername);
ELSEIF len(ipostcode) > 0 THEN
    (Select customerid, customername, postcode, accountnumber from dbName.customers
        WHERE postcode = ipostcode);
ELSE 
    (Select customerid, customername, postcode, accountnumber from dbName.customers
        WHERE accountnumber = iaccountnumber);
end if;

END

我无法 select db.table 以执行 select。这有可能吗?或者有更好的解决方案吗?

您可以使用 prepared statement 来做到这一点。

一个非常基本的准备语句如下所示:

SET @stat = CONCAT('SELECT * FROM ', @tab'); 

PREPARE stmt FROM @stat; 
EXECUTE stmt; 
DEALLOCATE PREPARE stmt; 

编辑:最基本语句的完整示例,使用 if 语句为 'where' 和 'table' 子句设置变量,您应该没问题!

EDIT2:认为您不想使用传入参数的语句,已编辑查询。

EDIT3: 基本完成了存储过程,你可以使用CALL test('dbname.tablename')来调用这个过程你在这里提供的参数是表名/dbname.tablename.

CREATE DEFINER=`user`@`%` PROCEDURE `test`(IN tbl VARCHAR(255))
BEGIN
DECLARE cols VARCHAR(255);
DECLARE conditions VARCHAR(255);

SET cols = 'customerid, customername, postcode, accountnumber';


IF LENGTH(icustomername) > 0 THEN 
SET conditions = CONCAT("customername = '", icustomername, "'");

ELSEIF len(ipostcode) > 0 THEN 
SET conditions = CONCAT("postcode = '", ipostcode, "'");

ELSE SET conditions = CONCAT("accountnumber = '", iaccountnumber , "'");
END IF;

    SET @stat = CONCAT('SELECT ', cols, ' FROM ', tbl, ' WHERE ', conditions );
    PREPARE stmt from @stat;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END

-------
CALL test('tablename');