Question

How do you set multiple varchar variables to latter use in multiple select staments?

The documentation has an integer example

SET (NEW_VAR.SALARY, NEW_VAR.COMM) = (50000, 8000);  

I can't figure out how to do the same for a varchar

SET (NEW_VAR.var, NEW_VAR.var1) = ('%hello%','%world%');
SELECT 
  *
FROM 
 fooSchema.barTable AS b
WHERE 
  b.first_name like new_var.var and
  b.last_name like new_var.var1;
Was it helpful?

Solution

As Mustaccio said, you could use variables between a compound statement, a trigger or a routine. For your example (a trigger):

CREATE TRIGGER trigger1
  AFTER insert ON mytable
  REFERENCING NEW AS NEW_VAR
  FOR EACH ROW
BEGIN

DECLARE val INT;
SET (NEW_VAR.var, NEW_VAR.var1) = ('%hello%','%world%');
SELECT col INTO val
  FROM fooSchema.barTable AS b
  WHERE b.first_name like new_var.var
  AND b.last_name like new_var.var1;

END @

Or in a compound statement

BEGIN
 DECLARE var varchar(32);
 DECLARE var1 varchar(32);
 DECLARE val INT;
  SET (NEW_VAR.var, NEW_VAR.var1) = ('%hello%','%world%');
 SELECT col INTO val
   FROM fooSchema.barTable AS b
   WHERE b.first_name like new_var.var
   AND b.last_name like new_var.var1;
END @

Note that I used an extra variable for the output of the select. A query like this should return just one row. Otherwise, you should use a cursor.

Remember that you should execute these scripts with the following option:

db2 -td@ -f yourFilename.sql
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top