简体   繁体   中英

Dynamically pass table name to a query db2

I need to do COUNT from table, which name is build dynamically and store the value

Tried two approaches, unsuccessful:

SET COUNT = (SELECT COUNT(*) FROM BUILD_FUNCTION_NAME(a,b))


SET NAME  = BUILD_FUNCTION_NAME(a,b)
SET COUNT = ( SELECT COUNT(*) FROM NAME)

If it's DB2 for LUW, then try this:

--#SET TERMINATOR @

CREATE OR REPLACE FUNCTION GET_COUNT(P_TABNAME VARCHAR(256))
RETURNS BIGINT
BEGIN
  DECLARE V_RC BIGINT;
  PREPARE S1 FROM 'SET ? = (SELECT COUNT(1) FROM '||P_TABNAME||')';
  EXECUTE S1 INTO V_RC;
  RETURN V_RC;
END@

VALUES GET_COUNT('SYSCAT.TABLES')@
VALUES GET_COUNT('SYSCAT.COLUMNS')@
VALUES GET_COUNT('(SELECT 1 FROM SYSCAT.TABLES WHERE TABSCHEMA LIKE ''SYS%'')')@

You can pass even an arbitrary SELECT statement into such a function as a parameter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM