我正在尝试编写一个程序,其中databasename是动态的,并且取自where子句。 到目前为止,我已经得到了这个:
CREATE PROCEDURE Test
(IN DBName VARCHAR(100), OUT RowCount DEC(10,2))
BEGIN
DECLARE SqlStr VARCHAR(1000);
DECLARE C1 CURSOR FOR S1;
SET SqlStr = 'SELECT count(*) FROM '|| DBNAME || '.MyTable ';
PREPARE S1 FROM SqlStr;
OPEN C1 USING DBName;
FETCH C1 INTO RowCount;
CLOSE C1;
END;
我现在需要添加这样的东西:
WHERE DBName = (SELECT 'firstpart||EnvName||' FROM EnvTable
WHERE EnvName = (SELECT EnvName FROM EnvTable WHERE Flag = 1 AND Priority = (SELECT MIN(Priority) FROM EnvTable))
有什么想法吗?我可以在调用程序时添加它吗?
答案 0 :(得分:0)
听起来你只需要一个变量来使它更具动态性:
CREATE PROCEDURE Test
(OUT RowCount DEC(10,2))
BEGIN
DECLARE SqlStr VARCHAR(1000);
DECLARE DBName VARCHAR(100);
DECLARE C1 CURSOR FOR S1;
/*Get your DBName variable loaded using SELECT INTO*/
SELECT 'firstpart' || EnvName INTO DBName
FROM EnvTable
WHERE Flag = 1 AND Priority = (SELECT MIN(Priority) FROM EnvTable);
/*and continue what you were doing*/
SET SqlStr = 'SELECT count(*) FROM '|| DBName || '.MyTable ';
PREPARE S1 FROM SqlStr;
OPEN C1 USING DBName;
FETCH C1 INTO RowCount;
CLOSE C1;
END;
我不确定你试图用firstpart||envname
做什么,但是这应该会让你陷入困境。基本上你只需要制作一个sql语句来制作你的dbname
变量,然后在第二个查询中使用它。