How to store the result of a select query into a variable(IBM DB2)? - db2

I am trying to save the result of a query into a variable. I am using IBM DB2, but I can only store the result if I am declaring the variable inside a procedure.
My code is:
DECLARE #myvar INTEGER;
SET #myvar = (SELECT MAX(ID) FROM S0SCSQMS.S0SRPTCNAME);
and I receive the following errors:
For the first line:"SQL0104N An unexpected token "INTEGER" was found following "DECLARE #myvar ". Expected tokens may include: "END-OF-STATEMENT". LINE NUMBER=1. SQLSTATE=42601"
The error code does not tell me much. I looked for it on the IBM documentation.
Looking forward for an answer.
Thank you.

try this (work on iseries db2 v7r1)
CREATE OR REPLACE VARIABLE myvar INTEGER ;
SET myvar = (SELECT max( id_xp_dossier) FROM cilgprod.xp_dossier);
DROP VARIABLE myvar;

Related

SQL0628N with MODIFIES SQL DATA when creating a table function

I am trying to encapsulate the functionality from this sample code here, inside a Table-Function.
I can run the sample alone without any problem.
But when I create a table function, just with a single call to OPEN_CURSOR , I receive SQL0577N
CREATE FUNCTION ROW_CHECKSUM
( IN sSchema VARCHAR(128) ,
IN sTable VARCHAR(128) ,
IN sColumnList VARCHAR(1024) ,
IN sWhere VARCHAR(1023),
IN iRows INTEGER
)
RETURNS TABLE (ROW_PK_VALUES VARCHAR(3000), CHECKSUM INTEGER )
LANGUAGE SQL
SPECIFIC ROW_CHECKSUM
--NO EXTERNAL ACTION
--MODIFIES SQL DATA
--NOT DETERMINISTIC
BEGIN
DECLARE iCheckSum INTEGER ;
DECLARE sKyes VARCHAR(1024) ;
DECLARE iCursor INTEGER;
DECLARE sQuery VARCHAR(32000) ;
SET sQuery = 'SELECT ' || sColumnList || ' FROM "' || sSchema || '"."' || sTable || '" WHERE ' || sWhere || ' FETCH FIRST ' || TO_CHAR(iRows) || ' ONLY' ;
CALL DBMS_SQL.OPEN_CURSOR(iCursor);
--CALL DBMS_SQL.PARSE(iCursor, sQuery, DBMS_SQL.native) ;
--PIPE (sKeys, iCheckSum) ;
--PIPE ('abcd', 1234) ;
RETURN ;
END
----
SQL0577N User defined routine "DB2ADMIN.ROW_CHECKSUM" (specific name "")
attempted to modify data but was not defined as MODIFIES SQL DATA. LINE
NUMBER=33. SQLSTATE=38002
it seems, OPEN_CURSOR demands to have the MODIFY SQL DATA specified.. ok.. let's go!
But, when I specify it, then I get the following error, instead:
SQL0628N Multiple or conflicting keywords involving the "MODIFIES SQL DATA"
clause are present. LINE NUMBER=33. SQLSTATE=42613
The error details for -628 error is too generic and does not help me to determine what's really going on here.
I need to perform dynamic SQL queries using DBMS_SQL module, and return the result set using PIPE , like this other sample here.
I have been reading spread documentations the entire day.. and so far was not able to determine exactly what rule I am violating.
Also, found some inconsistencies on documentation, which I don't understand:
This page, says:
SQL table functions cannot contain compiled compound statements.
While, the Rules from RETURN statement says the opposite, and matches with PIPE sample code:
In an SQL table function using a compound SQL (compiled) statement, an expression, NULL, or fullselectcannot be specified. Rows are returned from the function using the PIPE statement and the RETURN statement is required as the last statement to execute when the function exits (SQLSTATE 2F005).
Appreciate any help!
Look at the note about the MODIFIES SQL DATA in the CREATE FUNCTION statement description:
4 Valid only for compiled scalar function definition and an inlined
table function definition.
But you can't use PIPE in an inlined function.
So, you want to use different functionalities, which can't be used together.
The inconsistency you found in the documentation is not related to you problem.

Dynamic cursor variable in DB2

I want to open a dynamic cursor variable.
CREATE OR REPLACE PROCEDURE TTT ()
P1: BEGIN
Declare cID char(5) ;
declare c1 cursor for s1 ;
declare stmt varchar(1000) ;
set cid = 'a' ;
Set stmt = 'select * from aaa where a = ?' ;
prePare s1 from stmt ;
open c1 using cid ;
END P1
I get error :
A.TTT - Deploy started.
Create stored procedure returns SQLCODE: -104, SQLSTATE: 42601.
A.TTT: 6: An unexpected token "" was found following "". Expected tokens may include: "".. SQLCODE=-104, SQLSTATE=42601, DRIVER=3.69.56
An unexpected token "" was found following "". Expected tokens may include: "".. SQLCODE=-104, SQLSTATE=42601, DRIVER=3.69.56
A.TTT - Deploy failed.
A.TTT - Roll back completed successfully.
The cause of the error is that the code ignores the documented rules for the order of statements in a compound-SQL block.
One of the rules is that the cursor declaration(s) must appear after all other declared variables and before the start of the SQL PL code block.
So in your question, the order of the variables should be:
Declare cID char(5) ;
declare stmt varchar(1000) ;
declare c1 cursor for s1 ;
For Db2-LUW at current version these rules for compound SQL blocks are here.
To return a resultSet to the caller or the client, remember to add with return to caller or with return to client in the declare c1 cursor line, along with adding dynamic result sets 1 in the procedure definition.
To consume the cursor (i.e. to fetch from it) inside the stored procedure code then you do not need these things.
Your jdbc driver is very old, so plan to upgrade it to a better supported version. You can download the latest versions via this site https://www.ibm.com/support/pages/db2-jdbc-driver-versions-and-downloads
You can also make the error messages more verbose by appending an additional attribute to the connection string URL ;retrieveMessagesFromServerOnGetMessage=true;
This can speed up your ability to solve trivial programming problems when learning.

Compare variables declared in Snowflake Stored procedure

I got a stored procedure as below
CREATE OR REPLACE PROCEDURE SP12
(argument1 VARCHAR,argument2 VARCHAR
)
if (argument1 <> argument2) { return N1 } else { return N2}
The issue is iam getting error while comparing argument1 <> argument2 (need to compare not equal to).
Is this correct method.
Thanks
is the the complete code for your Stored Procedure or is it just a snippet? If it is the full code then I suggest that you read the documentation again: CREATE PROCEDURE
You need a RETURNS statement in the header
How are you declaring/assigning values to N1 and N2?
If these suggestions don't help then please provide the full SP Code (if this is just a snippet) and also the error message you are getting

DB2 procedure call literal error

I'm trying to call a DB2 procedure using DBeaver.
The syntax I'm using is this:
{ call db.procedure_name ('1234','2345','3456') }
Then I get an error saying:
"Literal replacement prasing failed for procedure call... Failing SQL
text..."
When I call the same procedure like this:
{ call db.procedure_name (?,?,?) }
and insert the parameters manually it executes.
I'm quite new to DB2 and IBM troubleshooting sites aren't much of a help.
Can you guys help me out? Thanks.
Try call db.procedure_name (:1,:2,:3)
or alternatively, create global variables for each parameter
create or replace variable p1 integer default 123;
create or replace variable p2 decimal(5,2) default 123.45;
create or replace variable p3 char(5);
set p3 = '12345';
call db.procedure_name (p1,p2,p3);

I can create a stored procure with invalid user defined function names in it

I just noticed that I could alter my stored procedure code with a misspelled user defined function in it.
I noticed that at 1st time I execute the SP.
Is there any way to get a compile error when an SP include an invalid user-defined function name in it?
At compile time? No.
You can, however, use some of SQL's dependency objects (if using MS SQL) to find problems just after deployment, or as part of your beta testing. Aaron Bertran has a pretty nice article rounding up the options, depending upon the version of SQL Server.
Here is an example using SQL Server 2008 sys object called sql_expression_dependencies
CREATE FUNCTION dbo.scalarTest
(
#input1 INT,
#input2 INT
)
RETURNS INT
AS
BEGIN
-- Declare the return variable here
DECLARE #ResultVar int
-- Add the T-SQL statements to compute the return value here
SELECT #ResultVar = #input1 * #input2
-- Return the result of the function
RETURN #ResultVar
END
GO
--Fn Works!
SELECT dbo.ScalarTest(2,2)
GO
CREATE PROCEDURE dbo.procTest
AS
BEGIN
SELECT TOP 1 dbo.scalarTest(3, 3) as procResult
FROM sys.objects
END
GO
--Sproc Works!
EXEC dbo.procTest
GO
--Remove a dependency needed by our sproc
DROP FUNCTION dbo.scalarTest
GO
--Does anything have a broken dependency? YES
SELECT OBJECT_NAME(referencing_id) AS referencing_entity_name,
referenced_entity_name, *
FROM sys.sql_expression_dependencies
WHERE referenced_id IS NULL --dependency is missing
GO
--Does it work? No
EXEC dbo.procTest
GO