How to execute an SQL string in DB2

db2
22,861

Solution 1

Do you mean executing a dynamic SQL string? Something like:

DECLARE stmt VARCHAR(1000);
DECLARE my_table VARCHAR(50);
SET my_table = 'DEPT_'||deptNumber;
SET stmt = 'SELECT * FROM '||my_table;
PREPARE s1 FROM stmt;
EXECUTE s1;

You can only do that in a stored proc though. One defined as CREATE PROCEDURE GetDeptInfo (deptNumber VARCHAR(5)) for this example. Read about EXECUTE and PREPARE in the db2 docs http://publib.boulder.ibm.com/infocenter/db2luw/v9r5/index.jsp

Solution 2

After days of researching I found how to write and run dynamic SQL on DB2:

create or replace procedure Search ()

    BEGIN

       DECLARE v_dynamicSql varchar(2000);
       SET v_dynamicSql = 'INSERT INTO dictonary(name) values(' || 'dynamicSQL in db2' ||')';

       EXECUTE IMMEDIATE v_dynamicSql;

    END;

Hope to help someone.

Share:
22,861
reggieboyYEAH
Author by

reggieboyYEAH

Updated on July 09, 2022

Comments

  • reggieboyYEAH
    reggieboyYEAH almost 2 years

    How do I execute an SQL string statement in DB2? I'm using IBM Data Studio.