How to execute compound sql in DB2

Abhinav picture Abhinav · Oct 19, 2012 · Viewed 12.6k times · Source

I am facing a challenge trying to understand DB2 sql (note, I am coming from MS SQL Server) :P.

Here is a scenario, I have got 2 tables one has IDs and other details, second one has lot of other info corresponding to each ID.

  ID              Info for ID
_______      ____> _______
|     |     /      |     |
|  T1 |<---------> |  T2 |
|_____|     \____> |_____|

Coming from SQL Server, I am used to running scripts like:

Declare @ID  int
Declare @ID1 int

select @ID=ID from T1 where col1 = @ID1

select * from T2 where ID = @ID

This all runs fine there and gives me an ID corresponding ID1 which can further be used to obtain all info about ID from T2.

Sadly, in DB2 this explodes right in my face, I am scared if I will execute this query one more time, it will disown me forever :(.

I did some research and wrote this (am even stuck at variable declaration).

--#SET TERMINATOR @
BEGIN ATOMIC
DECLARE UID char(30);
END @

For others it worked great, but I am getting following error:

BEGIN ATOMIC
DECLARE UID char(30);
END

ILLEGAL USE OF KEYWORD ATOMIC.  TOKEN  WAS EXPECTED. SQLCODE=-199, SQLSTATE=42601, DRIVER=3.63.108

Other Info:

IBM DB2 for z/OS V9.1 IBM Data Studio V3.1.1.0

[EDIT: using DECLARE] Another thing I tried that did not work for:

CREATE VARIABLE UID CHAR(30) DEFAULT 'USERID'; 
select * from testdb2.T1 A WHERE A.UID=v_UID;
--some other activity goes here
--and here
DROP VARIABLE UID;

TIA, Abhinav


Update on May 13th, 2016 (Friday the 13th)

Creating a stored proc is the only way of fixing this :(

Answer

AngocA picture AngocA · Oct 21, 2012

Your command works fine in DB2 10 for LUW. The data studio version does not matter, as it works the same from the CLP. I tested this code in the sample database:

BEGIN ATOMIC
 DECLARE UID char(30);
 SET UID = 200280;
 SELECT FIRSTNME, LASTNAME FROM ANDRES.EMPLOYEE WHERE EMPNO = UID;
END @

Probably, the z/OS version you are using does not support inline SQL (Begin atomic). I am not a zOS DBA, and I know there are many SQL differences between LUW, iSeries and zOS.

Please check the cross-platform compatibility. This is a very good blog to understand the problem: https://www.ibm.com/developerworks/mydeveloperworks/blogs/SQLTips4DB2LUW/entry/crossplatformsqlrefv4?lang=en