Declare a variable in DB2 SQL

I_AM_JARROD picture I_AM_JARROD · Jun 2, 2011 · Viewed 101.9k times · Source

Does anyone know how to run the following SQL Server code in DB2?

I am converting SQL Server scripts so that they will run on a DB2 system and am having some problems wrapping my head around the use of variables in DB2.

T-SQL code

This is obviously not the actual code but works well as an example.

DECLARE @INPUT_VALUE INT
SET INPUT_VALUE = 4756

SELECT *
FROM TABLE1
WHERE TABLE1.COLUMN1 = @INPUT_VALUE

Answer

Michael Sharek picture Michael Sharek · Jun 2, 2011

I imagine this forum posting, which I quote fully below, should answer the question.


Inside a procedure, function, or trigger definition, or in a dynamic SQL statement (embedded in a host program):

BEGIN ATOMIC
 DECLARE example VARCHAR(15) ;
 SET example = 'welcome' ;
 SELECT *
 FROM   tablename
 WHERE  column1 = example ;
END

or (in any environment):

WITH t(example) AS (VALUES('welcome'))
SELECT *
FROM   tablename, t
WHERE  column1 = example

or (although this is probably not what you want, since the variable needs to be created just once, but can be used thereafter by everybody although its content will be private on a per-user basis):

CREATE VARIABLE example VARCHAR(15) ;
SET example = 'welcome' ;
SELECT *
FROM   tablename
WHERE  column1 = example ;