I'm trying to write a procedure where the databasename is dynamic and is taken from a where clause. So far I have got this:
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;
I would need to add something like this now:
WHERE DBName = (SELECT 'firstpart||EnvName||' FROM EnvTable
WHERE EnvName = (SELECT EnvName FROM EnvTable WHERE Flag = 1 AND Priority = (SELECT MIN(Priority) FROM EnvTable))
Any ideas? Can I add this when I call the procedure?
Sounds like you just need a variable to make this more dynamic:
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;
I'm not sure what you were trying to do with firstpart||envname
, but this should get you in the ballpark. Essentially you just need to craft a sql statement that makes your dbname
variable and then use that in your second query.