How to fix syntax error while converting procedure to function? - postgresql

I am working on conversion of stored procedure of SQL server to stored function in PostgreSQL. I converted stored procedure to function. After conversion i run this script in pgadmin but it gives syntax error near if condition.
Stored Function:
CREATE OR REPLACE FUNCTION getuserdepartmentlist(p_nUserID bigInt,p_sRole varchar(100),p_nInstID bigInt = 0) RETURNS TEXT
AS $BODY$
----get dept list for non admin users
DECLARE v_DeptID bigint;
v_DeptIDList text;
v_isAdmin int;
v_isPM int;
v_isDelgate int;
BEGIN
v_DeptIDList :='';
v_isAdmin :=POSITION('Admin' IN p_sRole);
v_isPM :=POSITION('PM' IN p_sRole);
v_isDelgate :=POSITION('Delegate' IN p_sRole);
--Cursor Declaration for Admin/pm
DECLARE DeptCursor1 CURSOR FOR
SELECT department.ndept_id
FROM department
WHERE ninst_id = p_nInstID;
--Cursor Declaration for non Admin/pm
DECLARE DeptCursor2 CURSOR FOR
SELECT department.ndept_id
FROM users INNER JOIN
permission ON users.nuser_id = permission.nuser_id INNER JOIN
userrolemapping ON users.nuser_id = userrolemapping.nuser_id INNER JOIN
department ON permission.ndept_inst = department.ninst_id
AND department.ninst_id = p_nInstID
WHERE
users.nuser_id = p_nUserID and
spermission_type <> 'N' AND
permission.sperm_level = 'D' AND
users.bis_active = 1 AND
userrolemapping.nrole_id NOT IN
(SELECT nrole_id
FROM roles
WHERE srole_desc in ('Admin','PM'))
Union
SELECT department.ndept_id
FROM users
INNER JOIN permission ON users.nuser_id = permission.nuser_id
INNER JOIN userrolemapping ON users.nuser_id = userrolemapping.nuser_id
INNER JOIN department ON permission.ndept_inst = department.ninst_id
AND department.ninst_id = p_nInstID
WHERE
users.nuser_id = p_nUserID and
spermission_type <> 'N' AND
permission.sperm_level = 'I' AND
users.bis_active = 1 AND
userrolemapping.nrole_id NOT IN
(SELECT nrole_id
FROM roles
WHERE srole_desc in ('Admin','PM'));
IF (v_isAdmin > 0) OR (v_isPM > 0) OR (v_isDelgate >0)
THEN
--Cursor for Admin & PM
OPEN DeptCursor1;
FETCH NEXT FROM; DeptCursor1
INTO v_DeptID
WHILE FOUND
LOOP
v_DeptIDList := v_DeptIDList || '' || cast(v_DeptID as varchar(1)) || ',';
-- Get the next vendor.
FETCH NEXT FROM; DeptCursor1
INTO v_DeptID
END LOOP;
CLOSE DeptCursor1;
ELSE
--Cursor for Non Admin
OPEN DeptCursor2;
FETCH NEXT FROM; DeptCursor2
INTO v_DeptID
WHILE FOUND
LOOP
v_DeptIDList := v_DeptIDList || '' || cast(v_DeptID as varchar(1)) || ',';
-- Get the next vendor.
FETCH NEXT FROM; DeptCursor2
INTO v_DeptID
END LOOP;
CLOSE DeptCursor2;
END IF;
RETURN(v_DeptIDList);
END;
$$LANGUAGE plpgsql;
Error:
It is showing syntax error near if condition .I added error code below:
ERROR: syntax error at or near "IF"
LINE 61: IF (v_isAdmin > 0) OR (v_isPM > 0) OR (v_isDelgate >0)
^

This code is working fine with no errors.Cursor declaration is wrong in above code .
CREATE OR REPLACE FUNCTION getuserdepartmentlist(p_nUserID bigInt,p_sRole varchar(100),p_nInstID bigInt = 0)
RETURNS TEXT
AS
$BODY$
----get dept list for non admin users
DECLARE v_DeptID bigint;
v_DeptIDList text;
v_isAdmin int;
v_isPM int;
v_isDelgate int;
--Cursor Declaration for Admin/pm
DECLARE DeptCursor1 CURSOR FOR
SELECT department.ndept_id
FROM department
WHERE ninst_id = p_nInstID;
--Cursor Declaration for non Admin/pm
DECLARE DeptCursor2 CURSOR FOR
SELECT department.ndept_id
FROM users INNER JOIN
permission ON users.nuser_id = permission.nuser_id INNER JOIN
userrolemapping ON users.nuser_id = userrolemapping.nuser_id INNER JOIN
department ON permission.ndept_inst = department.ninst_id
AND department.ninst_id = p_nInstID
WHERE
users.nuser_id = p_nUserID and
spermission_type <> 'N' AND
permission.sperm_level = 'D' AND
users.bis_active = 1 AND
userrolemapping.nrole_id NOT IN
(SELECT nrole_id
FROM roles
WHERE srole_desc in ('Admin','PM'))
Union
SELECT department.ndept_id
FROM users INNER JOIN
permission ON users.nuser_id = permission.nuser_id INNER JOIN
userrolemapping ON users.nuser_id = userrolemapping.nuser_id INNER JOIN
department ON permission.ndept_inst = department.ninst_id
AND department.ninst_id = p_nInstID
WHERE
users.nuser_id = p_nUserID and
spermission_type <> 'N' AND
permission.sperm_level = 'I' AND
users.bis_active = 1 AND
userrolemapping.nrole_id NOT IN
(SELECT nrole_id
FROM roles
WHERE srole_desc in ('Admin','PM'));
BEGIN
v_DeptIDList :='';
v_isAdmin :=POSITION('Admin' IN p_sRole);
v_isPM :=POSITION('PM' IN p_sRole);
v_isDelgate :=POSITION('Delegate' IN p_sRole);
IF (v_isAdmin > 0) OR (v_isPM > 0) OR (v_isDelgate >0)
THEN
--Cursor for Admin & PM
OPEN DeptCursor1;
FETCH NEXT FROM DeptCursor1
INTO v_DeptID;
WHILE FOUND
LOOP
v_DeptIDList := v_DeptIDList || '' || cast(v_DeptID as varchar(1)) || ',';
-- Get the next vendor.
FETCH NEXT FROM DeptCursor1
INTO v_DeptID;
END LOOP;
CLOSE DeptCursor1;
ELSE
--Cursor for Non Admin
OPEN DeptCursor2;
FETCH NEXT FROM DeptCursor2
INTO v_DeptID;
WHILE FOUND
LOOP
v_DeptIDList := v_DeptIDList || '' || cast(v_DeptID as varchar(1)) || ',';
-- Get the next vendor.
FETCH NEXT FROM DeptCursor2
INTO v_DeptID;
END LOOP;
CLOSE DeptCursor2;
END IF;
--End cursor declaration
if len(v_DeptIDList)> 0 then
v_DeptIDList := SUBSTRING(v_DeptIDList,1,len(v_DeptIDList)-1);
else
v_DeptIDList :='0';
end if;
RETURN(v_DeptIDList);
END;
$BODY$
LANGUAGE plpgsql;

Related

Optimize very long stored procedure

I have stored procedure like this. I am posting body of procedure it has too many parameters and I have to many control for cheking warehouse activities.
And it becomes huge and I cant control it. What ll be the best aproach for optimizing this.
DECLARE #ORDERFICHEREF INT =488
DECLARE #STFICHEREF INT =560
DECLARE #CLIENTREF INT =608
DECLARE #BARCODE VARCHAR(50)='1536011000010'
DECLARE #ISPARTIAL BIT=0
DECLARE #TERMINALREF INT=1
DECLARE #PARAMETERREF INT=0
DECLARE #PARTIALAMOUNT FLOAT=1
DECLARE #PARTIALUOMREF INT=59
DECLARE #PARTIALCONVFACT1 INT =1
DECLARE #PARTIALCONVFACT2 INT =50
DECLARE #RESULT INT
DECLARE #FICHENO VARCHAR(20)
DECLARE #STATUS SMALLINT
DECLARE #BRANCH SMALLINT
DECLARE #SOURCEINDEX SMALLINT
DECLARE #BARCODEREF INT
DECLARE #ITEMREF INT
DECLARE #VARIANTREF INT
DECLARE #USREF INT
DECLARE #UOMREF INT
DECLARE #CONVFACT1 FLOAT
DECLARE #CONVFACT2 FLOAT
DECLARE #LSTAMOUNT FLOAT
DECLARE #USELABELUNITA INT
DECLARE #CHECKTYPE INT
DECLARE #ISEAN BIT
DECLARE #BARCODESPECODE VARCHAR(50)
DECLARE #PRICE FLOAT
SET #ISEAN=0
SET #CHECKTYPE =-1
SET #RESULT=0
DECLARE #SHIPINFOREF INT
SELECT #FICHENO =ORF.FICHENO,#STATUS=ORF.[STATUS],#BRANCH=ORF.BRANCH,#SOURCEINDEX=ORF.SOURCEINDEX
FROM ORDERFICHE ORF
INNER JOIN ORDERFICHE_TERMINAL ORFT ON ORF.LOGICALREF=ORFT.ORDERFICHEREF
WHERE ORF.LOGICALREF=#ORDERFICHEREF AND ORFT.TERMINALREF=#TERMINALREF
IF (#STATUS IS NULL OR (#STATUS NOT IN (0,1,6)))
BEGIN
SET #RESULT=14 --Fişe terminal atanmış ve fiş statusu tamamlandıdan küçük olacak
GOTO RESULT
END
SELECT
#BARCODEREF=LBL.LOGICALREF,
#ITEMREF=LBL.ITEMREF,
#VARIANTREF=LBL.VARIANTREF,
#UOMREF=LBL.UOMREF,
#USREF=LBL.USREF,
#CONVFACT1 = LBL.CONVFACT1,
#CONVFACT2 = LBL.CONVFACT2,
#LSTAMOUNT=SUM(CAST(CAST(STL.AMOUNT*STL.CONVFACT2/STL.CONVFACT1*(2-IOCODE)/ABS(2-IOCODE) AS NUMERIC(28,6)) AS FLOAT)),
#BARCODESPECODE = LBL.SPECODE
FROM LABEL_CARD LBL
LEFT OUTER JOIN STLINE STL ON LBL.LOGICALREF=STL.BARCODEREF AND STL.BRANCH=#BRANCH AND STL.SOURCEINDEX=#SOURCEINDEX
WHERE LBL.BARCODE=#BARCODE
GROUP BY LBL.LOGICALREF,LBL.ITEMREF,LBL.VARIANTREF,LBL.USREF,LBL.UOMREF,LBL.CONVFACT2,LBL.CONVFACT1,LBL.AMOUNT,STL.BRANCH,STL.SOURCEINDEX,LBL.SPECODE
--BARKOD - CARİ,SEVKİYAT ADRES KONTROLU
DECLARE #LABELCLINETREF INT
DECLARE #LABELLGORFICHEREF INT
DECLARE #LABELLGORFLINEREF INT
DECLARE #LABELSHIPINFOREF INT
IF(#BARCODEREF IS NOT NULL AND (SELECT CONVERT(BIT,VALUE) FROM ORDER_PARAMETER WHERE PARAMETERREF=86)=0) --Cari hesap için yazdırılmış etiket farklı cariye satılsın mı?
BEGIN
SELECT #SHIPINFOREF=SHIPINFOREF FROM STFICHE WHERE LOGICALREF=#STFICHEREF
SELECT #LABELCLINETREF=CLIENTREF,#LABELLGORFICHEREF=LGORFICHEREF,#LABELLGORFLINEREF=LGORFLINEREF,#LABELSHIPINFOREF=SHIPINFOREF
FROM LABEL_CARD_LGREFERENCE WHERE BARCODEREF=#BARCODEREF AND ISCANCELLED=0
IF(#LABELCLINETREF<>#CLIENTREF)
BEGIN
SET #RESULT=57 -- BAŞKA CARİ İÇİN YAZDIRILMIŞ ETİKET
GOTO RESULT
END
IF (ISNULL(#LABELSHIPINFOREF,0)>0)
BEGIN
IF(ISNULL(#LABELSHIPINFOREF,0)<>ISNULL(#SHIPINFOREF,0))
BEGIN
SET #RESULT=58 -- SEVKİYAT ADRESLERİ FARKLI
GOTO RESULT
END
END
END
IF (#BARCODEREF IS NULL )
BEGIN
DECLARE #EANCHARCOUNT INT
SELECT #EANCHARCOUNT=ISNULL(VALUE,0) FROM ORDER_PARAMETER WHERE PARAMETERREF=60
IF #EANCHARCOUNT>0
BEGIN
SET #BARCODE=LEFT(#BARCODE,#EANCHARCOUNT)
END
SELECT #ITEMREF=UB.ITEMREF,#VARIANTREF=ISNULL(UB.VARIANTREF,0),#UOMREF=UB.UNITLINEREF,#USREF=ITM.UNITSETREF,#CONVFACT1 = IUA.CONVFACT1,#CONVFACT2 =IUA.CONVFACT2
FROM {0}..LG_{1}_UNITBARCODE UB
JOIN {0}..LG_{1}_ITEMS ITM ON ITM.LOGICALREF=UB.ITEMREF
JOIN {0}..LG_{1}_ITMUNITA IUA ON IUA.UNITLINEREF=UB.UNITLINEREF AND IUA.LOGICALREF=UB.ITMUNITAREF AND UB.VARIANTREF=IUA.VARIANTREF
WHERE UB.TYP IN (0,1) AND UB.BARCODE=#BARCODE
IF ISNULL(#ITEMREF,0)=0
BEGIN
SET #RESULT=1 -- #ITEMREF NULL GELİYORSA EAN BARKOD YOK --Barkod LABEL_CARD'da ya sa UNITBARCODE da olmalı
GOTO RESULT
END
SET #ISEAN=1
SELECT #CHECKTYPE=CONVERT(INT,VALUE) FROM ORDER_PARAMETER WHERE PARAMETERREF=53
IF(#CHECKTYPE=0)
BEGIN
SELECT #LSTAMOUNT=SUM(CAST(CAST(AMOUNT*CONVFACT2/CONVFACT1*(2-IOCODE)/ABS(2-IOCODE) AS NUMERIC(28,6)) AS FLOAT))
FROM STLINE
WHERE BRANCH=#BRANCH AND SOURCEINDEX=#SOURCEINDEX AND ITEMREF=#ITEMREF AND VARIANTREF=#VARIANTREF AND BARCODEREF IS NULL
END
IF(#CHECKTYPE=1)
BEGIN
SELECT #LSTAMOUNT=SUM(CAST(CAST(AMOUNT*(2.5-IOCODE)/ABS(2.5-IOCODE)*(UINFO2/UINFO1) AS NUMERIC(28,6)) AS FLOAT))
FROM {0}..LG_{1}_{2}_STLINE
WHERE SOURCEINDEX=#SOURCEINDEX AND STOCKREF=#ITEMREF AND VARIANTREF=#VARIANTREF AND CANCELLED=0 AND LPRODSTAT = 0 AND UINFO1>0 AND UINFO2>0
END
IF((SELECT CONVERT(BIT,VALUE) FROM ORDER_PARAMETER WHERE PARAMETERREF=54)=1)
BEGIN
SET #PARTIALAMOUNT=1
SET #PARTIALUOMREF = #UOMREF
SET #PARTIALCONVFACT1 = #CONVFACT1
SET #PARTIALCONVFACT2 = #CONVFACT2
END
IF(#CHECKTYPE=1)
BEGIN
DECLARE #BACKAMOUNT FLOAT
SELECT #BACKAMOUNT=ISNULL(CAST(CAST(SUM(STL.AMOUNT*STL.CONVFACT2/STL.CONVFACT1) AS NUMERIC(28,6)) AS FLOAT) ,0)
FROM STLINE STL
INNER JOIN ORDERFICHE ORF ON ORF.LOGICALREF=STL.ORDERFICHEREF
WHERE ORF.STATUS<>3 AND STL.IOCODE=4 AND ITEMREF=#ITEMREF AND VARIANTREF=#VARIANTREF AND BARCODEREF IS NULL AND ORF.SOURCEINDEX=#SOURCEINDEX
SET #LSTAMOUNT=#LSTAMOUNT-#BACKAMOUNT
END
END
ELSE
BEGIN
--PARAMETEREREF=44
IF((SELECT DBO.FNC_EXPIRATIONDATE (#BARCODEREF,44))=1)
BEGIN
SET #RESULT=46
GOTO RESULT
END
END
IF(#CHECKTYPE<>2)
BEGIN
IF (#LSTAMOUNT IS NULL )
BEGIN
IF #CHECKTYPE=-1 AND EXISTS (SELECT NULL
FROM STLINE
WHERE BARCODEREF=#BARCODEREF AND (BRANCH<>#BRANCH OR SOURCEINDEX <> #SOURCEINDEX)
GROUP BY BARCODEREF
HAVING SUM(CAST(CAST(AMOUNT*(2-IOCODE)/ABS(2-IOCODE)*(CONVFACT2/CONVFACT1) AS NUMERIC(28,6)) AS FLOAT))>0)
BEGIN
SET #RESULT=55 --Barkod başka bir ambarda
GOTO RESULT
END
IF #CHECKTYPE=0 AND EXISTS (SELECT NULL
FROM STLINE
WHERE ITEMREF=#ITEMREF AND VARIANTREF=#VARIANTREF AND BARCODEREF IS NULL AND (BRANCH<>#BRANCH OR SOURCEINDEX <> #SOURCEINDEX)
GROUP BY ITEMREF,VARIANTREF,USREF
HAVING SUM(CAST(CAST(AMOUNT*(2-IOCODE)/ABS(2-IOCODE)*(CONVFACT2/CONVFACT1) AS NUMERIC(28,6)) AS FLOAT))>0)
BEGIN
SET #RESULT=55 --Barkod başka bir ambarda
GOTO RESULT
END
IF #CHECKTYPE=1 AND EXISTS (SELECT NULL
FROM {0}..LG_{1}_{2}_STLINE
WHERE STOCKREF=#ITEMREF AND VARIANTREF=#VARIANTREF AND CANCELLED=0 AND LPRODSTAT = 0 AND UINFO1>0 AND UINFO2>0 AND SOURCEINDEX <> #SOURCEINDEX
GROUP BY STOCKREF,VARIANTREF,USREF
HAVING SUM(CAST(CAST(AMOUNT*(2.5-IOCODE)/ABS(2.5-IOCODE)*(UINFO2/UINFO1) AS NUMERIC(28,6)) AS FLOAT))>0)
BEGIN
SET #RESULT=55 --Barkod başka bir ambarda
GOTO RESULT
END
SET #RESULT=2 --Barkod Stokta olmalı - Girişi yapılmamış ürün
GOTO RESULT
END
IF (#LSTAMOUNT<=0)
BEGIN
IF EXISTS (SELECT 1 FROM STLINE WHERE STFICHEREF=#STFICHEREF AND BARCODEREF=#BARCODEREF)
BEGIN
SET #RESULT=15 --Barkod Stokta olmalı - Mevcut emirde okutulmuş
GOTO RESULT
END
ELSE
BEGIN
SET #RESULT=3 --Barkod Stokta olmalı - Çıkışı yapılmış
GOTO RESULT
END
END
END
IF((#ISPARTIAL=0 OR #ISEAN=1) AND #PARTIALAMOUNT IS NOT NULL)
BEGIN
SET #LSTAMOUNT=#PARTIALAMOUNT
SET #UOMREF = #PARTIALUOMREF
SET #CONVFACT1 = #PARTIALCONVFACT1
SET #CONVFACT2 = #PARTIALCONVFACT2
END
IF EXISTS (SELECT 1 FROM ORDERLINE WHERE ORDERFICHEREF=#ORDERFICHEREF AND STFICHEREF=#STFICHEREF)
BEGIN
DECLARE #ORLCOUNT INT
SELECT #USELABELUNITA=USELABELCARDUNITA FROM LABEL_PARAMETERS WHERE LOGICALREF=1
SELECT #ORLCOUNT=COUNT(LOGICALREF) FROM ORDERLINE WHERE STFICHEREF=#STFICHEREF AND ITEMREF=#ITEMREF AND VARIANTREF=#VARIANTREF AND USREF = #USREF
IF (ISNULL(#ORLCOUNT,0)=0)
BEGIN
SET #RESULT=13 --ITEMREF emirde olmalı
GOTO RESULT
END
IF (#ISEAN=1 AND ISNULL(#PARTIALAMOUNT,0)=0)
BEGIN
SET #RESULT=11
GOTO RESULT
END
IF(#ISPARTIAL=0 AND #ISEAN=0)
BEGIN
IF NOT EXISTS(SELECT NULL FROM ORDERLINE ORL
INNER JOIN LABEL_CARD_UNITA LBLA ON LBLA.BARCODEREF = #BARCODEREF AND ORL.UOMREF = LBLA.UOMREF
WHERE ORL.STFICHEREF=#STFICHEREF AND ORL.ITEMREF=#ITEMREF AND ORL.VARIANTREF=#VARIANTREF)
BEGIN
IF #USELABELUNITA=1
BEGIN
SET #RESULT=54 --etiket birim miktarı girilmelidir.
GOTO RESULT
END
END
DECLARE #TOAMOUNT FLOAT
DECLARE #TSAMOUNT FLOAT
SELECT #TOAMOUNT=CAST(CAST(SUM(ORL.AMOUNT*CASE WHEN LCU.LOGICALREF IS NULL THEN CASE WHEN #USELABELUNITA =1 THEN 0 ELSE ORL.CONVFACT2/ORL.CONVFACT1 END ELSE LCU.CONVFACT2/LCU.CONVFACT1 END)AS NUMERIC(28,6)) AS FLOAT)
FROM ORDERLINE ORL
LEFT OUTER JOIN LABEL_CARD_UNITA LCU ON LCU.BARCODEREF = #BARCODEREF AND ORL.UOMREF = LCU.UOMREF
WHERE ORL.STFICHEREF=#STFICHEREF AND ORL.ITEMREF=#ITEMREF AND ORL.VARIANTREF=#VARIANTREF
SELECT #TSAMOUNT=CAST(CAST(SUM(STL.AMOUNT*(STL.CONVFACT2/STL.CONVFACT1))AS NUMERIC(28,6)) AS FLOAT)
FROM ORDERLINE ORL
INNER JOIN STLINE STL ON ORL.LOGICALREF = STL.ORDERLINEREF
WHERE ORL.STFICHEREF=#STFICHEREF AND ORL.ITEMREF=#ITEMREF AND ORL.VARIANTREF=#VARIANTREF
--Parçalı seri barkod emir miktar aşımı kontrolü için parçalı miktar ana birime çevriliyor.
DECLARE #MAINAMOUNT FLOAT
SET #MAINAMOUNT=#LSTAMOUNT
IF(#ISPARTIAL=0 AND #ISEAN=0 AND #PARTIALAMOUNT IS NOT NULL)
BEGIN
SET #MAINAMOUNT=#MAINAMOUNT*#CONVFACT2/#CONVFACT1
END
--IF (#MAINAMOUNT+ ISNULL(#TSAMOUNT,0)> ISNULL(#TOAMOUNT,0))
IF EXISTS(SELECT * FROM ORDER_PARAMETER WHERE PARAMETERREF=118 AND VALUE=0)
BEGIN
IF (CAST(CAST((ISNULL(#MAINAMOUNT,0)+ISNULL(#TSAMOUNT,0))AS NUMERIC(28,6))AS FLOAT)> ISNULL(CAST(CAST(#TOAMOUNT AS NUMERIC(28,6)) AS FLOAT),0))
BEGIN
SET #RESULT=25 --Emir miktarı aşılmamalı
GOTO RESULT
END
END
END
IF((#ISEAN=1) AND #PARTIALAMOUNT IS NOT NULL)
BEGIN
DECLARE #PTOAMOUNT FLOAT
DECLARE #PTSAMOUNT FLOAT
SELECT #PTOAMOUNT=ORL.AMOUNT,#PTSAMOUNT=CAST(CAST(SUM(STL.AMOUNT*(STL.CONVFACT2/STL.CONVFACT1))AS NUMERIC(28,6)) AS FLOAT) FROM ORDERLINE ORL
LEFT OUTER JOIN STLINE STL ON ORL.LOGICALREF=STL.ORDERLINEREF
WHERE ORL.STFICHEREF=#STFICHEREF AND ORL.ITEMREF=#ITEMREF AND ORL.VARIANTREF=#VARIANTREF AND ORL.UOMREF=#UOMREF
GROUP BY ORL.LOGICALREF,ORL.AMOUNT
IF EXISTS(SELECT * FROM ORDER_PARAMETER WHERE PARAMETERREF=118 AND VALUE=0)
BEGIN
IF(CAST(CAST((#LSTAMOUNT + ISNULL(#PTSAMOUNT,0))AS NUMERIC(28,6))AS FLOAT) > ISNULL(#PTOAMOUNT,0))
BEGIN
SET #RESULT=25 --Emir miktarı aşılmamalı
GOTO RESULT
END
END
END
END
DECLARE #FIFOCONTROL INT
SELECT #FIFOCONTROL=DBO.FNC_ENTRYDATE(#BARCODEREF,#BRANCH,#SOURCEINDEX,#PARAMETERREF)
IF #FIFOCONTROL>0
BEGIN
SET #RESULT=24
GOTO RESULT
END
IF(#ISEAN=0)
BEGIN
DECLARE #ISCOUNTING SMALLINT
SELECT #ISCOUNTING=DBO.FNC_ISCOUNTING(#BRANCH,#SOURCEINDEX,#ITEMREF,#VARIANTREF,#BARCODEREF)
IF (#ISCOUNTING=2) --SAYIMDA OKUTULMAMIS MALZEME
BEGIN
SET #RESULT=21
GOTO RESULT
END
END
IF (#ISPARTIAL=1 OR (#ISEAN=1 AND ISNULL(#PARTIALAMOUNT,0)=0))
BEGIN
SET #RESULT=11 --miktar girilmeli
GOTO RESULT
END
-- HAREKET ÖZEL KODU
DECLARE #SPECODE VARCHAR(50)
IF EXISTS(SELECT * FROM ORDER_PARAMETER WHERE PARAMETERREF=101 AND VALUE=1)
BEGIN
IF (#ISEAN=0)
BEGIN
SET #SPECODE = #BARCODESPECODE
END
ELSE IF (#ISEAN=1)
BEGIN
SET #SPECODE = #EANSPECODE
END
END
DECLARE #ORDERLINEREF INT
DECLARE #DATE DATETIME
SET #ORDERLINEREF=NULL
IF (ISNULL(#ORLCOUNT,0)>1)
BEGIN
DECLARE #CUOMREF INT
DECLARE #COAMOUNT FLOAT
DECLARE #CSAMOUNT FLOAT
DECLARE #CURRAMOUNT FLOAT
DECLARE #CCONVFACT1 FLOAT
DECLARE #CCONVFACT2 FLOAT
DECLARE CURSOR_SORDER CURSOR FOR SELECT LOGICALREF,AMOUNT,UOMREF,CONVFACT1,CONVFACT2 FROM ORDERLINE WHERE STFICHEREF=#STFICHEREF AND ITEMREF=#ITEMREF AND VARIANTREF=#VARIANTREF ORDER BY (CASE WHEN UOMREF=#UOMREF THEN 0 ELSE 1 END),ISNULL(LGORFICHEREF,2147483647)
OPEN CURSOR_SORDER
FETCH NEXT FROM CURSOR_SORDER INTO #ORDERLINEREF,#COAMOUNT,#CUOMREF,#CCONVFACT1,#CCONVFACT2
WHILE (##FETCH_STATUS = 0)
BEGIN
IF (ISNULL(#LSTAMOUNT,0)<=0)
BEGIN
BREAK
END
SET #CURRAMOUNT=0
IF((#ISEAN=1 OR #ISPARTIAL=0) AND #PARTIALAMOUNT IS NOT NULL)
BEGIN
SET #CURRAMOUNT=#LSTAMOUNT
--SET #CONVFACT1 = #CCONVFACT1
--SET #CONVFACT2 = #CCONVFACT2
END
ELSE
BEGIN
SELECT #CURRAMOUNT=#LSTAMOUNT*(CONVFACT1/CONVFACT2),#CONVFACT1=CONVFACT1,#CONVFACT2=CONVFACT2 FROM LABEL_CARD_UNITA WHERE BARCODEREF =#BARCODEREF AND UOMREF =#CUOMREF
END
IF (ISNULL(#USELABELUNITA,0)=0 AND #CURRAMOUNT =0)
BEGIN
SET #CURRAMOUNT = #LSTAMOUNT*#CCONVFACT1/#CCONVFACT2
SET #CONVFACT1 = #CCONVFACT1
SET #CONVFACT2 = #CCONVFACT2
END
SELECT #CSAMOUNT=ISNULL(SUM(CAST(CAST(AMOUNT AS NUMERIC(28,6)) AS FLOAT)),0) FROM STLINE WHERE STFICHEREF=#STFICHEREF AND ORDERLINEREF=#ORDERLINEREF AND ITEMREF=#ITEMREF AND VARIANTREF=#VARIANTREF AND UOMREF=#CUOMREF
IF (#COAMOUNT>#CSAMOUNT AND ISNULL(#CURRAMOUNT,0)>0)
BEGIN
IF (#COAMOUNT >= #CSAMOUNT + (#CURRAMOUNT))
BEGIN
SET #LSTAMOUNT=0
END
ELSE
BEGIN
SET #CURRAMOUNT = (#COAMOUNT - #CSAMOUNT)
SET #LSTAMOUNT=#LSTAMOUNT-#CURRAMOUNT
END
SET #DATE=GETDATE()
--SELECT 'bir', #STFICHEREF,8,4,#ITEMREF,#VARIANTREF,#BARCODEREF,#CURRAMOUNT,#CUOMREF,#USREF,#CONVFACT1,#CONVFACT2,#CLIENTREF,#BRANCH,#SOURCEINDEX,NULL,NULL,#DATE,#ORDERFICHEREF,#ORDERLINEREF,NULL,NULL,NULL,#TERMINALREF,#SPECODE
EXEC MOB_STLINE_INSERT #STFICHEREF,8,4,#ITEMREF,#VARIANTREF,#BARCODEREF,#CURRAMOUNT,#CUOMREF,#USREF,#CONVFACT1,#CONVFACT2,#CLIENTREF,#BRANCH,#SOURCEINDEX,NULL,NULL,#DATE,#ORDERFICHEREF,#ORDERLINEREF,NULL,NULL,NULL,#TERMINALREF,#SPECODE
END
FETCH NEXT FROM CURSOR_SORDER INTO #ORDERLINEREF,#COAMOUNT,#CUOMREF,#CCONVFACT1,#CCONVFACT2
END
CLOSE CURSOR_SORDER
DEALLOCATE CURSOR_SORDER
END
ELSE
BEGIN
DECLARE #LUSTAMOUNT FLOAT
SET #DATE=GETDATE()
IF (ISNULL(#ORLCOUNT,0)=1)
BEGIN
DECLARE #OCONVFACT1 FLOAT
DECLARE #OCONVFACT2 FLOAT
SELECT #ORDERLINEREF=LOGICALREF,#UOMREF=UOMREF,#OCONVFACT1=CONVFACT1,#OCONVFACT2=CONVFACT2 FROM ORDERLINE WHERE STFICHEREF=#STFICHEREF AND ITEMREF=#ITEMREF AND VARIANTREF=#VARIANTREF
IF((#ISEAN=1 OR #ISPARTIAL=0) AND #PARTIALAMOUNT IS NOT NULL)
BEGIN
SET #LUSTAMOUNT=#LSTAMOUNT
END
ELSE
BEGIN
SELECT #LUSTAMOUNT=#LSTAMOUNT*CONVFACT1/CONVFACT2,#CONVFACT1=CONVFACT1,#CONVFACT2=CONVFACT2 FROM LABEL_CARD_UNITA WHERE BARCODEREF =#BARCODEREF AND UOMREF =#UOMREF
IF (#LUSTAMOUNT IS NULL)
BEGIN
SET #LUSTAMOUNT = #LSTAMOUNT*#OCONVFACT1/#OCONVFACT2
SET #CONVFACT1=#OCONVFACT1
SET #CONVFACT2=#OCONVFACT2
END
END
END
IF #LUSTAMOUNT IS NULL
BEGIN
IF((#ISEAN=1 OR #ISPARTIAL=0) AND #PARTIALAMOUNT IS NOT NULL)
BEGIN
SET #LUSTAMOUNT=#LSTAMOUNT
END
ELSE
BEGIN
SET #LUSTAMOUNT=#LSTAMOUNT*#CONVFACT1/#CONVFACT2
END
END
--SELECT 'iki', #STFICHEREF,8,4,#ITEMREF,#BARCODEREF,ISNULL(#LUSTAMOUNT,#LSTAMOUNT),#UOMREF,#USREF,#CONVFACT1,#CONVFACT2,#CLIENTREF,#BRANCH,#SOURCEINDEX,NULL,NULL,#DATE,#ORDERFICHEREF,#ORDERLINEREF,NULL,NULL,NULL,#TERMINALREF,#SPECODE
EXEC MOB_STLINE_INSERT #STFICHEREF,8,4,#ITEMREF,#VARIANTREF,#BARCODEREF,#LUSTAMOUNT,#UOMREF,#USREF,#CONVFACT1,#CONVFACT2,#CLIENTREF,#BRANCH,#SOURCEINDEX,NULL,NULL,#DATE,#ORDERFICHEREF,#ORDERLINEREF,NULL,NULL,NULL,#TERMINALREF,#SPECODE
END
IF (#STATUS=0 OR #STATUS=6)
BEGIN
UPDATE ORDERFICHE SET [STATUS]=1 WHERE LOGICALREF=#ORDERFICHEREF
INSERT INTO RECORD_LOG (MODULEREF,RECORDID,IDENTITYINFO,USERREF,TERMINALREF,PROCESSDATE,[TYPE],[DESCRIPTION])
VALUES (103,#ORDERFICHEREF,'Emir Numarası:' + ' ' + #FICHENO,NULL,#TERMINALREF,#DATE,16,'Durumu : Yükleniyor')
END
RESULT:
SELECT ISNULL(#RESULT,0) [RESULT]
IF (#ISPARTIAL=1 OR #ISEAN=1)
BEGIN
SELECT ISNULL(#LSTAMOUNT,0) [LSTAMOUNT],#ISEAN [ISEAN],#CHECKTYPE [CHECKTYPE],(SELECT TOP 1 UOMREF FROM ORDERLINE WHERE STFICHEREF=#STFICHEREF AND ITEMREF=#ITEMREF AND VARIANTREF=#VARIANTREF ORDER BY (CASE WHEN UOMREF=#UOMREF THEN 0 ELSE 1 END),ISNULL(LGORFICHEREF,2147483647)) [ORDERUOMREF]
IF(#ISEAN=1)
BEGIN
SELECT UNL.LOGICALREF,UNL.CODE,UNL.MAINUNIT,ISNULL(ORL.CONVFACT1,ITMA.CONVFACT1) [CONVFACT1],ISNULL(ORL.CONVFACT2,ITMA.CONVFACT2) [CONVFACT2],
CASE WHEN ORL.LOGICALREF IS NULL THEN 0 ELSE 1 END [ORDERUNIT],
CASE WHEN ITMA.UNITLINEREF = #UOMREF THEN 1 ELSE 0 END [DEFAULTUNIT],
ORL.AMOUNT - SUM(CAST(CAST(ISNULL(STL.AMOUNT,0) AS NUMERIC(28,6)) AS FLOAT)) [OAMOUNT]
FROM {0}..LG_{1}_ITMUNITA ITMA
INNER JOIN {0}..LG_{1}_UNITSETL UNL ON ITMA.UNITLINEREF = UNL.LOGICALREF
LEFT OUTER JOIN ORDERLINE ORL ON ORL.ORDERFICHEREF = #ORDERFICHEREF AND ORL.STFICHEREF = #STFICHEREF AND ORL.ITEMREF = ITMA.ITEMREF AND ORL.VARIANTREF = ITMA.VARIANTREF AND ORL.UOMREF = ITMA.UNITLINEREF
LEFT OUTER JOIN STLINE STL ON ORL.LOGICALREF = STL.ORDERLINEREF
WHERE ITMA.ITEMREF = #ITEMREF AND ITMA.VARIANTREF = #VARIANTREF
GROUP BY UNL.LINENR,UNL.LOGICALREF,UNL.CODE,UNL.MAINUNIT,ORL.CONVFACT1,ITMA.CONVFACT1,ORL.CONVFACT2,ITMA.CONVFACT2,ORL.LOGICALREF,ITMA.UNITLINEREF,ORL.AMOUNT
ORDER BY UNL.LINENR
END
ELSE
BEGIN
IF((#USELABELUNITA=1 AND ISNULL(#ORLCOUNT,0)>0) OR (ISNULL(#ORLCOUNT,0)=0))
BEGIN
SELECT UNL.LOGICALREF,UNL.CODE,UNL.MAINUNIT,LBLA.CONVFACT1 [CONVFACT1],LBLA.CONVFACT2 [CONVFACT2],
CASE WHEN ORL.LOGICALREF IS NULL THEN 0 ELSE 1 END [ORDERUNIT],
CASE WHEN LBLA.UOMREF = #UOMREF THEN 1 ELSE 0 END [DEFAULTUNIT],
ORL.AMOUNT - SUM(CAST(CAST(ISNULL(STL.AMOUNT,0) AS NUMERIC(28,6)) AS FLOAT)) [OAMOUNT]
FROM LABEL_CARD_UNITA LBLA
INNER JOIN {0}..LG_{1}_UNITSETL UNL ON LBLA.UOMREF = UNL.LOGICALREF
LEFT OUTER JOIN ORDERLINE ORL ON ORL.ORDERFICHEREF = #ORDERFICHEREF AND ORL.STFICHEREF = #STFICHEREF AND ORL.ITEMREF = #ITEMREF AND ORL.VARIANTREF = #VARIANTREF AND ORL.UOMREF = LBLA.UOMREF
LEFT OUTER JOIN STLINE STL ON ORL.LOGICALREF = STL.ORDERLINEREF
WHERE LBLA.BARCODEREF = #BARCODEREF
GROUP BY UNL.LINENR,UNL.LOGICALREF,UNL.CODE,UNL.MAINUNIT,ORL.CONVFACT1,LBLA.CONVFACT1,ORL.CONVFACT2,LBLA.CONVFACT2,ORL.LOGICALREF,LBLA.UOMREF,ORL.AMOUNT
ORDER BY UNL.LINENR
END
ELSE IF(#USELABELUNITA=0 AND ISNULL(#ORLCOUNT,0)>0)
BEGIN
SELECT * FROM (
SELECT UNL.LINENR,UNL.LOGICALREF ,UNL.CODE,UNL.MAINUNIT,LBLA.CONVFACT1 [CONVFACT1],LBLA.CONVFACT2 [CONVFACT2],
CASE WHEN ORL.LOGICALREF IS NULL THEN 0 ELSE 1 END [ORDERUNIT],
CASE WHEN LBLA.UOMREF = #UOMREF THEN 1 ELSE 0 END [DEFAULTUNIT],
ORL.AMOUNT - SUM(CAST(CAST(ISNULL(STL.AMOUNT,0) AS NUMERIC(28,6)) AS FLOAT)) [OAMOUNT],ORL.LOGICALREF [ORDERLINEREF]
FROM LABEL_CARD_UNITA LBLA
INNER JOIN {0}..LG_{1}_UNITSETL UNL ON LBLA.UOMREF = UNL.LOGICALREF
LEFT OUTER JOIN ORDERLINE ORL ON ORL.ORDERFICHEREF = #ORDERFICHEREF AND ORL.STFICHEREF = #STFICHEREF AND ORL.ITEMREF = #ITEMREF AND ORL.VARIANTREF = #VARIANTREF AND ORL.UOMREF = LBLA.UOMREF
LEFT OUTER JOIN STLINE STL ON ORL.LOGICALREF = STL.ORDERLINEREF
WHERE LBLA.BARCODEREF = #BARCODEREF
GROUP BY UNL.LINENR,UNL.LOGICALREF,UNL.CODE,UNL.MAINUNIT,ORL.CONVFACT1,LBLA.CONVFACT1,ORL.CONVFACT2,LBLA.CONVFACT2,ORL.LOGICALREF,LBLA.UOMREF,ORL.AMOUNT
UNION ALL
SELECT UNL.LINENR,UNL.LOGICALREF ,UNL.CODE,UNL.MAINUNIT,LBLA.CONVFACT1 [CONVFACT1],LBLA.CONVFACT2 [CONVFACT2],
CASE WHEN ORL.LOGICALREF IS NULL THEN 0 ELSE 1 END [ORDERUNIT],
CASE WHEN LBLA.UOMREF = #UOMREF THEN 1 ELSE 0 END [DEFAULTUNIT],
ORL.AMOUNT - SUM(CAST(CAST(ISNULL(STL.AMOUNT,0) AS NUMERIC(28,6)) AS FLOAT)) [OAMOUNT],ORL.LOGICALREF [ORDERLINEREF]
FROM ORDERLINE ORL
INNER JOIN {0}..LG_{1}_UNITSETL UNL ON ORL.UOMREF = UNL.LOGICALREF
LEFT OUTER JOIN LABEL_CARD_UNITA LBLA ON ORL.UOMREF=LBLA.UOMREF
--AND ORL.UOMREF = LBLA.UOMREF
LEFT OUTER JOIN STLINE STL ON ORL.LOGICALREF = STL.ORDERLINEREF
WHERE LBLA.BARCODEREF = #BARCODEREF AND ORL.ORDERFICHEREF = #ORDERFICHEREF AND ORL.STFICHEREF = #STFICHEREF AND ORL.ITEMREF = #ITEMREF AND ORL.VARIANTREF = #VARIANTREF AND LBLA.LOGICALREF IS NULL
GROUP BY UNL.LINENR,UNL.LOGICALREF,UNL.CODE,UNL.MAINUNIT,ORL.CONVFACT1,LBLA.CONVFACT1,ORL.CONVFACT2,LBLA.CONVFACT2,ORL.LOGICALREF,LBLA.UOMREF,ORL.AMOUNT
) AS A
ORDER BY A.LINENR
END
END
END
It's so easy I just make every logic as sperate sp.
Before
SELECT #FICHENO =ORF.FICHENO,#STATUS=ORF.[STATUS],#BRANCH=ORF.BRANCH,#SOURCEINDEX=ORF.SOURCEINDEX
FROM ORDERFICHE ORF
INNER JOIN ORDERFICHE_TERMINAL ORFT ON ORF.LOGICALREF=ORFT.ORDERFICHEREF
WHERE ORF.LOGICALREF=#ORDERFICHEREF AND ORFT.TERMINALREF=#TERMINALREF
IF (#STATUS IS NULL OR (#STATUS NOT IN (0,1,6)))
BEGIN
SET #RESULT=14 --Fişe terminal atanmış ve fiş statusu tamamlandıdan küçük olacak
GOTO RESULT
END
After
EXEC PRX_MINT_FICHE_STATUS_CONTROL #ORDERFICHEREF,#TERMINALREF,#RESULT OUTPUT,#FICHENO OUTPUT,#BRANCH OUTPUT,#SOURCEINDEX OUTPUT
IF #RESULT>0
GOTO RESULT;
I write same code in the procedure i create output variables which i needed for next steps.

Postgres COPY command escapes new lines and tabs

I have a sql function:
CREATE OR REPLACE FUNCTION dump_func()
RETURNS void AS
$BODY$
DECLARE
r record;
loc varchar(100);
BEGIN
for r in (SELECT f.oid as oid, proname, pg_get_functiondef(f.oid) as src
FROM pg_catalog.pg_proc f
INNER JOIN pg_catalog.pg_namespace n ON (f.pronamespace = n.oid)
WHERE n.nspname = 'public') loop
loc = '/Users/raman/Desktop/functions/' || r.proname || '.sql';
raise notice '% - %', r.oid, loc;
raise notice 'func: %', r.src;
EXECUTE format('COPY (
SELECT pg_get_functiondef(f.oid)
FROM pg_catalog.pg_proc f
INNER JOIN pg_catalog.pg_namespace n ON (f.pronamespace = n.oid)
WHERE n.nspname = ''public'' and f.oid=%s
) TO ''%s'' ', r.oid, loc);
end loop;
end
$BODY$
LANGUAGE plpgsql;
which exports each db functions in postgres into a separate file using the COPY command. Everything works except that in the exported sql files new lines and tabs are escaped, for example:
CREATE OR REPLACE FUNCTION public.is_numeric(text)\n RETURNS boolean\n
LANGUAGE plpgsql\n IMMUTABLE\nAS $function$\nDECLARE x
NUMERIC;\nBEGIN\n x = $1::NUMERIC;\n RETURN TRUE;\nEXCEPTION
WHEN others THEN\n RETURN FALSE;\nEND;\n$function$\n
As you can see new lines and tabs are escaped, how to fix that?
Actually, this can be done. Hacky though it is you simply use regexp_split_to_table and split on the \n character. I was just trying to work out the same problem myself. Here's the code I wound up with:
DO $$
DECLARE
v_row record;
v_proname text;
v_sql text;
BEGIN
FOR v_row IN (
SELECT f.proname
FROM pg_catalog.pg_proc AS f
INNER JOIN pg_catalog.pg_namespace AS n ON (f.pronamespace = n.oid)
WHERE n.nspname = 'public' AND f.proisagg = false
) LOOP
SELECT v_row.proname::text INTO v_proname;
EXECUTE FORMAT('COPY (
SELECT regexp_split_to_table(regexp_replace(pg_get_functiondef(oid), ''\t'', '' '', ''g''), ''\n'')
FROM pg_catalog.pg_proc WHERE proname = ''%s'')
TO ''C:\pg\%s.sql'';'
, v_proname, v_proname);
END LOOP;
END $$
Andrew's answer is correct, helped me format it as well.
I came up with a similar function but to print all user defined functions in PSQL. Hope it helps to anyone who needs it:
CREATE OR REPLACE FUNCTION printFunctions(stage VARCHAR, ischema VARCHAR, file_path VARCHAR)
RETURNS VARCHAR AS
$$
DECLARE
func VARCHAR;
file_location TEXT;
BEGIN
FOR func IN SELECT procname FROM listfunctions()
LOOP
SELECT (file_path || '/' || func || '_' || stage || '.sql') INTO file_location;
IF (SELECT regexp_matches(func, '(pldb|plpg)')) IS NULL
THEN
EXECUTE 'COPY ' ||
'(SELECT regexp_split_to_table(regexp_replace(pg_get_functiondef(oid), ''\t'', '' '', ''g''),''\n'') from pg_proc where proname=' ||
'''' || func || '''' ||
' and pronamespace=(select oid from pg_namespace where nspname=' ||
'''' || ischema || ''''
')) TO ' || '''' || file_location || '''';
END IF;
END LOOP;
RETURN stage;
END
$$
LANGUAGE 'plpgsql';
You can call it with:
SELECT * FROM printFunctions('dev', 'public', '/tmp');

Postgres Function returning no results but when the same query returns results outside function

I am running a simple postgres function to return the count of rows. I am able to run the same query outside function with the output of raise option , but the function doesn't return any rows. I have tried different ways to produce results but unable to. Please find my function below,
CREATE OR REPLACE FUNCTION my_schema.usp_spellcheck3(SearchORItems_WithPipe varchar, site varchar, lan varchar, rows_display integer)
RETURNS TABLE (docmnt int) AS $BODY$
DECLARE
arrSearchTerms text[];
NewTerm varchar;
i integer;
AltSearch_withComma varchar;
AltSearch_withPipe varchar;
strDidYouMean varchar;
dpDidYouMean double precision;
txtDidYouMean Text;
SearchORItems_withComma varchar;
SearchORItems varchar;
SearchORItem varchar;
ws varchar;
arrSearchORItems_withComma varchar[];
BEGIN
strDidYouMean = 'DidYouMeanRow';
dpDidYouMean = 0.0;
txtDidYouMean = 'DidYouMeanRow';
ws = '''' || '%' || site || '%' || '''' ;
RAISE NOTICE '%', ws;
SearchORItems = REPLACE(SearchORItems_WithPipe, '|', ',');
SELECT regexp_split_to_array(SearchORItems, ',') INTO arrSearchORItems_withComma;
RAISE NOTICE '%', SearchORItems;
FOR i IN 1 .. coalesce(array_upper(arrSearchORItems_withComma, 1), 1) LOOP
IF (i = 1) THEN
SearchORItems_withComma = '''' || arrSearchORItems_withComma[i] || '''';
ELSE
SearchORItems_withComma = SearchORItems_withComma||','||'''' || arrSearchORItems_withComma[i] || '''';
END IF;
END LOOP;
RAISE NOTICE '%',SearchORItems_withComma;
SELECT COUNT(*) INTO res_count
FROM (
SELECT 1 FROM my_schema.features f , my_schema.documents d
WHERE term IN (SearchORItems_withComma)
AND d.docid = f.docid
AND d.url LIKE ws
GROUP BY f.docid, d.url) t;
RAISE NOTICE '%', res_count;
SearchORItem = 'SELECT COUNT(*) INTO res_count
FROM (SELECT 1 FROM my_schema.features f , my_schema.documents d
WHERE term IN ('||SearchORItems_withComma||')
AND d.docid = f.docid AND d.url LIKE ' || ws ||'
GROUP BY f.docid, d.url) t';
RAISE NOTICE '%',SearchORItem;
END;
$BODY$ LANGUAGE SQL VOLATILE;
this is my query output :
NOTICE: '%uni%'
NOTICE: daniel,data
NOTICE: 'daniel','data'
NOTICE: 0
NOTICE: select count(*) into res_count
from ( select 1 from my_schema.features f , my_schema.documents d
where term in ('daniel','data')
and d.docid=f.docid and d.url like '%uni%'
group by f.docid,d.url)t
Total query runtime: 16 ms.
0 rows retrieved.
I dont know where I'm going wrong, any help would be appreciated .. Thanks..
The simple reason that nothing is returned is that you have no RETURN statements in your code. When a function RETURNS TABLE you need to explicitly put one or more RETURN NEXT or RETURN QUERY statements in the body of your code, with a final RETURN statement to indicate the end of the function. See the documentation here: http://www.postgresql.org/docs/9.3/static/plpgsql-control-structures.html#PLPGSQL-STATEMENTS-RETURNING. What exactly you want to return is not clear but likely candidates are res_count and d.docid.
Other than that, your code could use a real clean-up reducing clutter like:
ws := '''%' || site || '%''' ;
instead of:
ws = '''' || '%' || site || '%' || '''' ;
and:
SELECT COUNT(*) INTO res_count
FROM my_schema.features f,
JOIN my_schema.documents d ON d.docid = f.docid
WHERE term IN (SearchORItems_withComma)
AND d.url LIKE ws
GROUP BY f.docid, d.url;
instead of:
SELECT COUNT(*) INTO res_count
FROM (
SELECT 1 FROM my_schema.features f , my_schema.documents d
WHERE term IN (SearchORItems_withComma)
AND d.docid = f.docid
AND d.url LIKE ws
GROUP BY f.docid, d.url) t;
And you should use the assignment operator (:=) instead of the equality operator in any plpgsql statement that is not a SQL statement.

Error with Query SELECT in cursor

I have problem with my select in cursor. Select works normal in other windows but I got error in procedure with cursor why ?
I change name of Tabele and Database but Select is OK outside this procedure
My error:
PL/SQL: ORA-04052:
ORA-00604:
ORA-03106:
CREATE OR REPLACE PROCEDURE ChangeDismissDate
IS
BEGIN
DECLARE
v_id VARCHAR2(40);
v_dateABC DATE;
v_dateDismiss DATE;
CURSOR cur IS
select emp.EMP_NO, abc.date, emp.DISMISS_DATE
from bazaabc.EmployeesDetails#BAZA_ABC abc,
employee_tab emp,
person_info_tab pin,
oracle_account oa
where bhd.emp_no = emp.EMP_NO
and pin.PERSON_ID = emp.EMP_NO
and oa.USERNAME = pin.USER_ID
and emp.EMP_NO in (
select pi.PERSON_ID from tab_person pi
where fu.active = 'TRUE'
and fu.IDENTITY = pi.USER_ID) AND emp.EMP_NO like '%L%'
and nvl(abc.date,to_date('20491231','yyyymmdd')) <> nvl(emp.DISMISS_DATE,to_date('20491231','yyyymmdd'));
BEGIN
OPEN cur;
LOOP
FETCH cur INTO v_id,v_dateABC,v_dateDismiss;
DBMS_OUTPUT.PUT_LINE('v_id: ' || v_id);
DBMS_OUTPUT.PUT_LINE('v_dateABC: ' || v_dateABC);
DBMS_OUTPUT.PUT_LINE('v_dateDismiss: ' ||v_dateDismiss );
EXIT WHEN cur%NOTFOUND;
END LOOP;
CLOSE cur;
END;
END;
/
Can you try with what errors you are getting by adding exception block
CREATE OR REPLACE PROCEDURE ChangeDismissDate
IS
BEGIN
DECLARE
v_id VARCHAR2(40);
v_dateABC DATE;
v_dateDismiss DATE;
CURSOR cur IS
select emp.EMP_NO, abc.date, emp.DISMISS_DATE
from bazaabc.EmployeesDetails#BAZA_ABC abc,
employee_tab emp,
person_info_tab pin,
oracle_account oa
where bhd.emp_no = emp.EMP_NO
and pin.PERSON_ID = emp.EMP_NO
and oa.USERNAME = pin.USER_ID
and emp.EMP_NO in (
select pi.PERSON_ID from tab_person pi
where fu.active = 'TRUE'
and fu.IDENTITY = pi.USER_ID)
AND emp.EMP_NO like '%L%'
and nvl(abc.date,to_date('20491231','yyyymmdd')) <>
nvl(emp.DISMISS_DATE,to_date('20491231','yyyymmdd'));
BEGIN
OPEN cur;
LOOP
FETCH cur INTO v_id,v_dateABC,v_dateDismiss;
DBMS_OUTPUT.PUT_LINE('v_id: ' || v_id);
DBMS_OUTPUT.PUT_LINE('v_dateABC: ' || v_dateABC);
DBMS_OUTPUT.PUT_LINE('v_dateDismiss: ' ||v_dateDismiss );
EXIT WHEN cur%NOTFOUND;
END LOOP;
CLOSE cur;
END;
EXCEPTION
WHEN NO_DATA_FOUND
THEN
DBMS_OUTPUT.put_line (DBMS_UTILITY.format_error_stack);
WHEN OTHERS
THEN
DBMS_OUTPUT.put_line (DBMS_UTILITY.format_error_stack);
END;
/

Running PostgreSQL stored procedures in SQL console

I have following stored procedure
CREATE FUNCTION runMortalityModel(a_user_id integer) RETURNS integer AS $$
DECLARE
t1 RECORD;
t2 RECORD;
numberOfDeaths integer;
BEGIN
SELECT person.id personId, person.age, condprobmin, condprobmax, random() experiment
INTO t1
FROM person, mortality_cond_prob
WHERE (user_id = a_user_id) and
(person.age = mortality_cond_prob.age);
SELECT personId
INTO t2
FROM t1
WHERE (tmp.condprobmin <= experiment) and (experiment <= tmp.condprobmax);
SELECT COUNT(*)
INTO numberOfDeaths
FROM t2;
RAISE 'numberOfDeaths=%', numberOfDeaths;
EXECUTE
'DELETE '
|| 'FROM person '
|| 'WHERE person.id IN '
|| t2;
RETURN numberOfDeaths;
END
$$ LANGUAGE plpgsql;
When I try to run this stored procedure using
SELECT runMortalityModel(1);
I get the error Relation »t1« doesn't exist.
How can I fix it?
Update 1: Changed the stored procedure declaration to
CREATE OR REPLACE FUNCTION runMortalityModel(a_user_id integer) RETURNS integer AS $$
DECLARE
t1 RECORD;
t2 RECORD;
numberOfDeaths integer;
BEGIN
EXECUTE 'SELECT person.id personId, person.age, condprobmin, condprobmax, random() experiment '
|| 'FROM person, mortality_cond_prob '
|| 'WHERE (user_id = ' || a_user_id || ') and '
|| '(person.age = mortality_cond_prob.age)'
INTO t1;
EXECUTE 'SELECT personId '
|| 'FROM ' || t1
|| ' WHERE (tmp.condprobmin <= experiment) and (experiment <= tmp.condprobmax)'
INTO t2;
EXECUTE 'SELECT COUNT(*) '
|| 'FROM ' || t2
INTO numberOfDeaths;
RAISE 'numberOfDeaths=%', numberOfDeaths;
EXECUTE
'DELETE '
|| 'FROM person '
|| 'WHERE person.id IN '
|| t2;
RETURN numberOfDeaths;
END
$$ LANGUAGE plpgsql;
I see several issues with original code:
You're trying to use RECORD variable as a relation, you should do ... FROM (SELECT t1.*) s instead;
I see no point to select 1 record, then do a query on that record and then perform count(*), you will always have either 0 or 1 as a result.
You second version looks much better, go for it.
This one seems to work. If you have better ideas, please tell them.
CREATE FUNCTION runMortalityModel(a_user_id integer) RETURNS integer AS $$
DECLARE
t1 RECORD;
curRecord RECORD;
numberOfDeaths integer;
BEGIN
numberOfDeaths := 0;
FOR curRecord IN
SELECT person.id personId, condprobmin, condprobmax, random() experiment
FROM person, mortality_cond_prob
WHERE (user_id = a_user_id) and
(person.age = mortality_cond_prob.age)
LOOP
IF (curRecord.condprobmin <= curRecord.experiment) AND (curRecord.experiment <= curRecord.condprobmax) THEN
EXECUTE
'DELETE '
|| 'FROM person '
|| 'WHERE person.id = ' || curRecord.personId;
numberOfDeaths := numberOfDeaths + 1;
END IF;
END LOOP;
RETURN numberOfDeaths;
END
$$ LANGUAGE plpgsql;