Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute an SQL string in DB2

Tags:

db2

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

like image 460
reggieboyYEAH Avatar asked Jan 19 '23 04:01

reggieboyYEAH


2 Answers

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

like image 143
MrG Avatar answered Jan 27 '23 21:01

MrG


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.

like image 39
zerone Avatar answered Jan 27 '23 21:01

zerone