Recursive Stored Procedures - sql

I found this code snipped (Source):
CREATE PROCEDURE rec_fib(n INT, OUT out_fib INT)
BEGIN
DECLARE n_1 INT;
DECLARE n_2 INT;
IF (n=0) THEN
SET out_fib=0;
ELSEIF (n=1) then
SET out_fib=1;
ELSE
CALL rec_fib(n-1,n_1);
CALL rec_fib(n-2,n_2);
SET out_fib=(n_1 + n_2);
END IF;
END
This code works with MySQL. In how far do I have to modify it to run on DB2? I cannot seem to find a running minimal example of an recursive stored procedure for DB2.

This works for me: (I haven't done more than make it work, so alternative coding could also work.)
First, add these two lines:
DECLARE n_3 INT;
DECLARE n_4 INT;
Then modify this small section:
ELSE
set n_3 = n - 1;
set n_4 = n - 2;
CALL rec_fib(n_3,n_1);
CALL rec_fib(n_4,n_2);
That's all. Runs on IBM i 6.1 DB2 UDB.

The following code is from SQL tips for DB2, written by Serge Rielau
CREATE OR REPLACE FUNCTION Fib(n INTEGER) RETURNS DECIMAL(31, 0)
BEGIN
DECLARE res DECIMAL(31, 0);
CASE WHEN n = 0 THEN
SET res = 0;
WHEN n = 1 THEN
SET res = 1;
WHEN n > 1 THEN
BEGIN
DECLARE stmt STATEMENT;
PREPARE stmt FROM 'SET ? = Fib(? - 1) + Fib(? - 2)';
EXECUTE stmt INTO res USING n, n;
END;
ELSE
SIGNAL SQLSTATE '78000' SET MESSAGE_TEXT = 'Bad input';
END CASE;
RETURN res;
END;
/
For more information, please check the source page of this code: https://www.ibm.com/developerworks/community/blogs/SQLTips4DB2LUW/entry/recursive_sql_pl?lang=en

Related

How to fix PLS-00103 error in case statement?

I"m using oracle sql developer and I'm trying to test case statements, but I keep getting errors ORA-06550 and PLS-00103.
set v_naujas_rizikos_lygis := 100;
begin
declare v_naujas_rizikos_lygis INT;
set v_naujas_rizikos_lygis :=225;
begin
case
when v_mokejimu_suma>0 and v_mokejimu_suma<100 then 1
when v_mokejimu_suma>100 and v_mokejimu_suma<200 then 2
when v_mokejimu_suma>200 and v_mokejimu_suma<300 then 3
end v_naujas_rizikos_lygis
print(v_naujas_rizikos_lygis);
I need my case statment to set a new value for my variable v_naujas_rizikos_lygis. Any ideas?
If think you mean
v_naujas_rizikos_lygis := case
when v_mokejimu_suma>0 and v_mokejimu_suma<100 then 1
when v_mokejimu_suma>100 and v_mokejimu_suma<200 then 2
when v_mokejimu_suma>200 and v_mokejimu_suma<300 then 3
else ...
end;
(replace ... with a default value)

Calling function with table valued parameters in Postgres

I have been facing a problem from since morning and have spent many hours but failed to call below given function.
Function definition:
CREATE OR REPLACE FUNCTION public.proc_mc2cdnpf_insertupdatev3(
tblnotesv3 typupdate_notesv3,
tbldoclinks typupdate_guidparameter,
iuserid integer,
shtmltext character varying,
OUT snoteid character varying,
OUT inoteid integer,
OUT inoteactivityid integer)
RETURNS record
LANGUAGE 'plpgsql'
COST 100
VOLATILE
AS $BODY$
#variable_conflict use_variable
declare sNote VARCHAR;
declare sLoggedInUser VARCHAR(20);
declare dtCurrDateTime timestamp;
declare iCurrDate int;
declare iCurrTime INT;
declare iNewNoteID INT;
BEGIN
/*
proc_MC2CDNPF_InsertUpdateV3
2018-04-23 Dennis Sebenick
2018-04-23
- Initial creation of new proc for storing additional HTML text value.
- This proc is going to help bridge the old note system to a new note storage method
2018-04-25
- Added iNoteID / iNoteActivityID for output
2018-06-01
- Update to typUpdate_NotesV3 - removed additional CDN rows for long text
2091-05-08
Rupali Shah
web 1753-added RTRIM(isnull(NOTE_HDQTRS,'')) while creating sNoteID
*/
/******************************
** File: proc_MC2CDNPF_InsertUpdateV3
** Desc: Insert/Update account notes
** Auth: Rupali Shah
** Date: 2019-05-08
**************************
** Change History
**************************
** Date Dev JIRA Description
**2019-05-08 Rupali Shah Web 1753 -added RTRIM(isnull(NOTE_HDQTRS,'')) while creating sNoteID
*******************************/
SELECT dtCurrDateTime = fnGetDate();
SELECT iCurrDate = fnMC2DateToMC2(dtCurrDateTime);
SELECT iCurrTime = fnMC2DateTimeToMC2(dtCurrDateTime);
/*==========================================
Retrieve Update fields from parameter
============================================*/
select
NoteID,
NOTE_NOTES,
NOTE_LOGGEDINUSER,
coalesce(NOTE_ID, 0)
INTO SNoteID,sNote,sLoggedInUser,iNewNoteID
from
tblNotesV3
LIMIT 1;
/************************************************
2018-04-18 DKS
Added in to update new note table
*************************************************/
IF (iNewNoteID > 0)
THEN
BEGIN
IF (LENGTH(sNote) > 0)
THEN
BEGIN
UPDATE
NoteDetails
SET
sNote = sNote,
sNoteHTML = sHTMLText,
iNoteEditedBy = iUserID,
dtNoteEdited = dtCurrDateTime
WHERE
iNoteID = iNewNoteID;
IF (ROWCOUNT = 0)
THEN
BEGIN
INSERT INTO
NoteDetails
(
iNoteType,
sNote,
sNoteHTML,
iNoteEnteredBy,
dtNoteEntered
)
VALUES
( 9, -- iNoteType - int
sNote, -- sNote - VARCHAR(max)
sHTMLText, -- sNoteHTML - VARCHAR(max)
iUserID, -- iNoteEnteredBy - int
dtCurrDateTime
) RETURNING iNewNoteID;
END;
END IF;
END;
END IF;
END;
ELSE
BEGIN
-- Inserting a New Activity
-- 2018-04-18 DKS
-- - Insert to new note table.
IF (LENGTH(sNote) > 0)
THEN
BEGIN
INSERT INTO
NoteDetails
(
iNoteType,
sNote,
sNoteHTML,
iNoteEnteredBy,
dtNoteEntered
)
VALUES
( 9, -- iNoteType - int
sNote, -- sNote - VARCHAR(max)
sHTMLText, -- sNoteHTML - VARCHAR(max)
iUserID, -- iNoteEnteredBy - int
dtCurrDateTime
) RETURNING iNewNoteID;
END;
END IF;
END;
END IF;
/************************************************
End new note table insert / update
*************************************************/
IF EXISTS(SELECT * FROM MC2CDNPF WHERE MC2CDNPF.iNoteID = iNoteID)
THEN
BEGIN
UPDATE
MC2CDNPF
SET
CDNNOTES = '',
CDNFDATE = fnMC2DateToMC2(TblNotesUpdate.NOTE_DDATE),
CDNREASN = TblNotesUpdate.NOTE_REASN,
CDNPRIOR = TblNotesUpdate.NOTE_PRIOR,
CDNTAGGED = TblNotesUpdate.NOTE_TAGGED,
iNoteID = iNewNoteID
FROM
MC2CDNPF
JOIN
tblNotesV3 TblNotesUpdate
ON
MC2CDNPF.iNoteID = TblNotesUpdate.NOTE_ID
WHERE
MC2CDNPF.CDNDSEQN = 1;
END;
ELSE
BEGIN
SELECT
TRIM(coalesce(NOTE_CMPANY,'')) ||
TRIM(coalesce(NOTE_BUSNSS,'')) ||
TRIM(coalesce(NOTE_CUSNBR,'')) ||
TRIM(coalesce(NOTE_ENTITY,'')) ||
TRIM(coalesce(NOTE_HDQTRS,'')) ||
CAST( iCurrDate AS VARCHAR(8)) ||
CAST( iCurrTime AS VARCHAR(10))
INTO sNoteID
FROM
tblNotesV3
LIMIT 1;
INSERT INTO
MC2CDNPF
(
CDNDSEQN,
CDNNOTES,
CDNCMPANY,
CDNCUSNBR,
CDNBUSNSS,
CDNENTITY,
CDNHDQTRS,
CDNRPTCON,
CDNFULNME,
CDNAGNIDN,
CDNDDATE,
CDNDTIME,
CDNREASN,
CDNTUSER,
CDNADATE,
CDNTAGGED,
CDNFDATE,
CDNPRIOR,
CDNDTASRC,
CDNODATE,
CDNOTIME,
iNoteID
)
SELECT
1,
'', -- 6/1/2018 DKS - no longer storing note in MC2CDNPF
coalesce(NOTE_CMPANY,''),
coalesce(NOTE_CUSNBR,''),
coalesce(NOTE_BUSNSS,''),
coalesce(NOTE_ENTITY,''),
coalesce(NOTE_HDQTRS,''),
coalesce(NOTE_RPTCON,''),
NOTE_FULNME,
coalesce(NOTE_AGNIDN,''),
iCurrDate,
iCurrTime,
NOTE_REASN,
NOTE_TUSER,
iCurrDate,
coalesce(NOTE_TAGGED,''),
iCurrDate,
NOTE_PRIOR,
coalesce(NOTE_DTASRC,''),
iCurrDate,
iCurrTime,
iNewNoteID
FROM
tblNotesV3 TblSource;
END;
END IF;
-- There are attachments to link
IF EXISTS(SELECT * FROM tblDocLinks)
THEN
BEGIN
CALL public.proc_Documents_AddLinkMultiple_LinkID (tblDocLinks, 9, 0, sNoteID, iUserID);
END;
END IF;
iNoteID := iNewNoteID;
iNoteActivityID := 0;
END;
$BODY$;
I am trying to call my function in following two ways:
Method1:
SELECT public.proc_MC2CDNPF_InsertUpdateV3
(
(SELECT w::typupdate_notesv3 FROM (TABLE tblnotesv31) w ) ,
(SELECT w1::typupdate_guidparameter FROM (TABLE tbldoclinks1) w1 ) ,
1,
'test text'
)
But it fails with following error:
ERROR: query has no destination for result data
HINT: If you want to
discard the results of a SELECT, use PERFORM instead. CONTEXT:
PL/pgSQL function
proc_mc2cdnpf_insertupdatev3(typupdate_notesv3,typupdate_guidparameter,integer,character
varying) line 41 at SQL statement SQL state: 42601
Method2:
SELECT *
from proc_MC2CDNPF_InsertUpdateV3
(
(SELECT w::typupdate_notesv3 FROM (TABLE tblnotesv31) w ) ,
(SELECT w1::typupdate_guidparameter FROM (TABLE tbldoclinks1) w1 ) ,
1,
'test text'
)
Again it failed saying:
ERROR: query has no destination for result data HINT: If you want to
discard the results of a SELECT, use PERFORM instead. CONTEXT:
PL/pgSQL function
proc_mc2cdnpf_insertupdatev3(typupdate_notesv3,typupdate_guidparameter,integer,character
varying) line 41 at SQL statement SQL state: 42601
Can please someone help me out that what's actually wrong with my function call?
Starting at line 41 (as the error message told you) you got:
SELECT dtCurrDateTime = fnGetDate();
SELECT iCurrDate = fnMC2DateToMC2(dtCurrDateTime);
SELECT iCurrTime = fnMC2DateTimeToMC2(dtCurrDateTime);
I assume you want to set the variables there. But you're doing it wrong. (It looks like you tried to use SQL Server syntax. Is this an attempt to port a function from SQL Server to Postgres? There are also BEGIN ... END blocks for IFs and ELSEs, which are unnecessary (but harmless) in Postgres but needed in SQL Server.)
Either use INTO:
SELECT fnGetDate() INTO dtCurrDateTime;
SELECT fnMC2DateToMC2(dtCurrDateTime) INTO iCurrDate;
SELECT fnMC2DateTimeToMC2(dtCurrDateTime) INTO iCurrTime;
Or, since you're not actually querying a table, simple assignments should work too:
dtCurrDateTime = fnGetDate();
iCurrDate = fnMC2DateToMC2(dtCurrDateTime);
iCurrTime = fnMC2DateTimeToMC2(dtCurrDateTime);
There might be other lines with the same mistake, you should check the whole code.

Create function in MonetDB

I'm trying to add a simple function in to monetDB at database level, which just does sum(n) and returns the result
create function sys.foo(number int)
returns int
begin
declare tsum int;
set tsum = 0;
while number > 0 do
set tsum = tsum + number;
set number = number -1;
end while;
return tsum;
end;
While attempting to execute the above code i'm seeing error as follows
[Error Code: 0, SQL State: 42000] syntax error, unexpected $end, expecting WHILE: end of input stream in "create function sys.foo(number int)
I could add the same function in to MySQL, and it works!!
>select sys.foo(10)
sys.foo(10)
-----------
55
Could some one please let me know whats going wrong here?
This works fine for me (Oct2014 release of MonetDB, Mac OS X)
➜ ~ mclient
Welcome to mclient, the MonetDB/SQL interactive terminal (unreleased)
Database: MonetDB v11.19.16 (unreleased), 'demo'
Type \q to quit, \? for a list of available commands
auto commit mode: on
sql>create function sys.foo(number int)
more>returns int
more>begin
more>declare tsum int;
more>set tsum = 0;
more>while number > 0 do
more>set tsum = tsum + number;
more>set number = number -1;
more>end while;
more>return tsum;
more>end;
operation successful (2.127ms)
sql>select sys.foo(10);
+------------------+
| foo_single_value |
+==================+
| 55 |
+------------------+
1 tuple (1.771ms)

SQL - Trying to add variable into string

I have a store procedure where I pass a path to the file like:
EXEC spMyPathFile
#PFile = 'C:\TFiles\Paths\Test_1.1_Version.txt'
What I'd like to do it loop through and be able to pass a number of versions of the file like 1.1 and 1.2 etc using:
DECLARE #intLp INT
DECLARE #a varchar(2)
SET #intLp = 1 WHILE (#intLp <2)
BEGIN IF #intLp = 1 BEGIN
SET #a = '1.1'
END
ELSE IF #intLp = 2
BEGIN
SET #a = '1.2'
END
EXEC spMyPathFile
#PFile = 'C:\TFiles\Paths\Test_'+#a+'_Version.txt'
SET #intLp = #intLp + 1
END
For some reason I get "Incorrect syntax near '+'." which is just before the #a. I'm obviously not joining my variable to my string properly.
Could someone give me an example of how this should look?
Change
EXEC spMyPathFile
#PFile = 'C:\TFiles\Paths\Test_'+#a+'_Version.txt'
to
declare #FileName varchar(100) = 'C:\TFiles\Paths\Test_' + #a + '_Version.txt'
EXEC spMyPathFile
#PFile = #FileName
Edit:
From MSDN - Specify Parameters
The parameter values supplied with a procedure call must be constants or a variable; a function name cannot be used as a parameter value. Variables can be user-defined or system variables such as ##spid.

SQL Server 2008 math fail

After hunting around on various forums for almost an hour, I've come to the conclusion that SQL server is slightly stupid about simple arithmetic.
I am attempting to utilize a function which, until recently seemed to work just fine. Upon changing out some of the values for a different set of information on the form in use, I get the odd behavior ahead.
The problem is that it is giving me the incorrect result as based on an excel spreadsheet formula.
The formula looks like this:
=IF(D8=0,0,(((D8*C12-C16)*(100-C13)/100+C16)/D8)+(C18*D8))
My SQL looks like this:
(((#DaysBilled * #ContractRate - #ActualPlanDed) * (100 - #InsCover) / 100 + #ActualPlanDed) / #DaysBilled) + (#CoPay * #DaysBilled)
Filling the variables with the given data looks like this:
(((11 * 433 - 15) * (100 - 344) / 100 + 15) / 11) + (15 * 11)
Even stranger, if I use the numbers above (adding .00 to the end of each value) manually in the server environment, it gives me -11405.1200000000
With the values I am giving, it should come out 166.36. Unfortunately, I am getting -886.83
Here is the entire function and how it is called:
ALTER FUNCTION Liability
(
#ClientGUID CHAR(32),
#RecordGUID CHAR(32),
#Type CHAR(3)
)
RETURNS DECIMAL(18,2) AS
BEGIN
DECLARE #ReturnValue decimal(18,2);
DECLARE #DaysBilled int;
DECLARE #ContractRate decimal(18,2);
DECLARE #ActualPlanDed decimal(18,2);
DECLARE #InsCover decimal(18,2);
DECLARE #CoPay decimal(18,2);
IF (#Type = 'RTC')
BEGIN
SELECT #DaysBilled = RTCDaysBilled,
#ContractRate = CAST(REPLACE(REPLACE(ContractRateRTC, ' ',''),'$', '') AS DECIMAL(6,2)),
#ActualPlanDed = RTCActualPlanDed,
#InsCover = InsRTCCover,
#CoPay = RTCCoPay
FROM AccountReconciliation1
WHERE #ClientGUID = tr_42b478f615484162b2391ef0b2c35ddc
AND #RecordGUID = tr_abb4effa0d9c4fe98c78cb4d2e21ba5d
END
IF (#Type = 'PHP')
BEGIN
SELECT #DaysBilled = PHPDaysBilled,
#ContractRate = CAST(REPLACE(REPLACE(ContractRatePHP, ' ',''),'$', '') AS DECIMAL(6,2)),
#ActualPlanDed = PHPActualPlanDed,
#InsCover = InsPHPCover,
#CoPay = PHPCoPay
FROM AccountReconciliation1
WHERE #ClientGUID = tr_42b478f615484162b2391ef0b2c35ddc
AND #RecordGUID = tr_abb4effa0d9c4fe98c78cb4d2e21ba5d
END
IF (#Type = 'IOP')
BEGIN
SELECT #DaysBilled = IOPDaysBilled,
#ContractRate = CAST(REPLACE(REPLACE(ContractRateIOP, ' ',''),'$', '') AS DECIMAL(6,2)),
#ActualPlanDed = IOPActualPlanDed,
#InsCover = InsIOPCover,
#CoPay = IOPCoPay
FROM AccountReconciliation1
WHERE #ClientGUID = tr_42b478f615484162b2391ef0b2c35ddc
AND #RecordGUID = tr_abb4effa0d9c4fe98c78cb4d2e21ba5d
END
IF (#DaysBilled <> 0)
BEGIN
SET #ReturnValue = (((#DaysBilled * #ContractRate - #ActualPlanDed)
*
(100 - #InsCover) / 100 + #ActualPlanDed)
/
#DaysBilled
)
+
(#CoPay * #DaysBilled)
END
ELSE
BEGIN
SET #ReturnValue = 0;
END
RETURN #ReturnValue;
END
It is called by running a select statement from our front-end, but the result is the same as calling the function from within management studio:
SELECT dbo.Liability('ClientID','RecordID','PHP') AS Liability
I have been reading about how a unary minus tends to break SQL's math handling, but I'm not entirely sure how to counteract it.
One last stupid trick with this function: It must remain a function. I cannot convert it into a stored procedure because it must be used with our front-end, which cannot utilize stored procedures.
Does SQL server even care about the parentheses? Or is it just ignoring them?
The calculation is correct, it differes of course if you are using float values
instead of integers.
For (((11 * 433 - 15) * (100 - 344) / 100 + 15) / 11) + (15 * 11)
a value around -886.xx depending in which places integers/floats are used is correct,
What makes you believe it should be 166.36?