WITH clause behavior in BEGIN END block PL/SQL [duplicate] - oracle

I am wanting to store a Rownum as a variable rather than use a costly Join.
I need to get this from a Select statement as the Rownum will be different on various environments so it cannot be a literal string in the code.
For context, this query is executed on Oracle Siebel CRM schema and it retrieves some products of specific type and attributes.
I tried using the following SQL code in Toad and Oracle SQL Developer, however I am getting the following error:
PLS-00428: an INTO clause is expected in this SELECT statement
Here is the code
DECLARE
PROD_ROW_ID varchar(10) := NULL;
BEGIN
SELECT ROW_ID INTO VIS_ROW_ID FROM SIEBEL.S_PROD_INT WHERE PART_NUM = 'S0146404';
BEGIN
SELECT rtrim(VIS.SERIAL_NUM) || ',' || rtrim(PLANID.DESC_TEXT) || ',' ||
CASE
WHEN PLANID.HIGH = 'TEST123'
THEN
CASE
WHEN to_date(PROD.START_DATE) + 30 > sysdate
THEN 'Y'
ELSE 'N'
END
ELSE 'N'
END
|| ',' || 'GB' || ',' ||
rtrim(to_char(PROD.START_DATE, 'YYYY-MM-DD'))
FROM SIEBEL.S_LST_OF_VAL PLANID
INNER JOIN SIEBEL.S_PROD_INT PROD
ON PROD.PART_NUM = PLANID.VAL
INNER JOIN SIEBEL.S_ASSET NETFLIX
ON PROD.PROD_ID = PROD.ROW_ID
INNER JOIN SIEBEL.S_ASSET VIS
ON VIS.PROM_INTEG_ID = PROD.PROM_INTEG_ID
INNER JOIN SIEBEL.S_PROD_INT VISPROD
ON VIS.PROD_ID = VISPROD.ROW_ID
WHERE PLANID.TYPE = 'Test Plan'
AND PLANID.ACTIVE_FLG = 'Y'
AND VISPROD.PART_NUM = VIS_ROW_ID
AND PROD.STATUS_CD = 'Active'
AND VIS.SERIAL_NUM IS NOT NULL;
END;
END;
/

In PLSQL block, columns of select statements must be assigned to variables, which is not the case in SQL statements.
The second BEGIN's SQL statement doesn't have INTO clause and that caused the error.
DECLARE
PROD_ROW_ID VARCHAR (10) := NULL;
VIS_ROW_ID NUMBER;
DSC VARCHAR (512);
BEGIN
SELECT ROW_ID
INTO VIS_ROW_ID
FROM SIEBEL.S_PROD_INT
WHERE PART_NUM = 'S0146404';
BEGIN
SELECT RTRIM (VIS.SERIAL_NUM)
|| ','
|| RTRIM (PLANID.DESC_TEXT)
|| ','
|| CASE
WHEN PLANID.HIGH = 'TEST123'
THEN
CASE
WHEN TO_DATE (PROD.START_DATE) + 30 > SYSDATE
THEN
'Y'
ELSE
'N'
END
ELSE
'N'
END
|| ','
|| 'GB'
|| ','
|| RTRIM (TO_CHAR (PROD.START_DATE, 'YYYY-MM-DD'))
INTO DSC
FROM SIEBEL.S_LST_OF_VAL PLANID
INNER JOIN SIEBEL.S_PROD_INT PROD
ON PROD.PART_NUM = PLANID.VAL
INNER JOIN SIEBEL.S_ASSET NETFLIX
ON PROD.PROD_ID = PROD.ROW_ID
INNER JOIN SIEBEL.S_ASSET VIS
ON VIS.PROM_INTEG_ID = PROD.PROM_INTEG_ID
INNER JOIN SIEBEL.S_PROD_INT VISPROD
ON VIS.PROD_ID = VISPROD.ROW_ID
WHERE PLANID.TYPE = 'Test Plan'
AND PLANID.ACTIVE_FLG = 'Y'
AND VISPROD.PART_NUM = VIS_ROW_ID
AND PROD.STATUS_CD = 'Active'
AND VIS.SERIAL_NUM IS NOT NULL;
END;
END;
/
References
http://docs.oracle.com/cd/E11882_01/appdev.112/e25519/static.htm#LNPLS00601
http://docs.oracle.com/cd/B19306_01/appdev.102/b14261/selectinto_statement.htm#CJAJAAIG
http://pls-00428.ora-code.com/

Related

Solving PL/SQL for loop variable string not resolving completely

I am trying to loop through multiple tables in a data mart and see how my TABLE_A joins to a TABLE_B based on a specific field (that changes with every loop). The variables for fields and tables resolve correctly in the DBMS_Output, but the query itself does not resovle to the full length. Instead, parts of the query are being cut off with each loop. How can I fix this?
My loop looks like this:
DECLARE
CURSOR c_tables is
SELECT
COLUMN_NAME
,JOIN_TABLE_NAME
FROM meself.test_loop ;
v_string1 varchar2(32767) := '';
BEGIN
FOR i IN c_tables LOOP
v_string1 := '
INSERT INTO myself.FIN_HASHKEY_MATCH
SELECT
x.TABLE_NAME
,x.JOIN_TABLE_NAME
,x.HASH_KEY_NAME
,x.MATCH_TYPE
,count(*) AS TOTALS
FROM
(
SELECT
DISTINCT a.'||i.COLUMN_NAME||'
,''' || i.JOIN_TABLE_NAME || ''' AS JOIN_TABLE_NAME
,''' || i.COLUMN_NAME || ''' AS HASH_KEY_NAME
, ''TABLE_A'' AS Table_Name
,(CASE
WHEN
a.'|| i.COLUMN_NAME || ' = z.' || i.COLUMN_NAME || ' THEN "MATCH"
ELSE "FAIL"
END) AS MATCH_TYPE
FROM DATAMART.TABLE_A a
LEFT JOIN (SELECT
DISTINCT '|| i.COLUMN_NAME ||'
FROM DATAMART.'|| i.JOIN_TABLE_NAME ||') z
ON a.'|| i.COLUMN_NAME ||' = z.'|| i.COLUMN_NAME ||'
) x
GROUP BY x.TABLE_NAME, x.JOIN_TABLE_NAME, x.HASH_KEY_NAME, x.MATCH_TYPE'
;
dbms_output.put_line( v_string1 );
--execute immediate v_string1;
END LOOP;
END;
**Which resolves to this (just showing 2 loops for simplicity). You will see the JOIN ON section is missing or incomplete before moving on to the next loop. **
INSERT INTO myself.FIN_HASHKEY_MATCH
SELECT
x.TABLE_NAME
,x.JOIN_TABLE_NAME
,x.HASH_KEY_NAME
,x.MATCH_TYPE
,count(*) AS TOTALS
FROM
(
SELECT
DISTINCT a.LINE_SCTGRY_D_SK
,'TABLE_B' AS JOIN_TABLE_NAME
,'LINE_SCTGRY_D_SK' AS HASH_KEY_NAME
,'TABLE_A' AS Table_Name
,(CASE
WHEN
a.LINE_SCTGRY_D_SK = z.LINE_SCTGRY_D_SK THEN "MATCH"
ELSE "FAIL"
END) AS MATCH_TYPE
FROM DATAMART.TABLE_A a
LEFT JOIN (SELECT
DISTINCT LINE_SCTGRY_D_SK
FROM DATAMART.TABLE_B
INSERT INTO myself.FIN_HASHKEY_MATCH
SELECT
x.TABLE_NAME
,x.JOIN_TABLE_NAME
,x.HASH_KEY_NAME
,x.MATCH_TYPE
,count(*) AS TOTALS
FROM
(
SELECT
DISTINCT a.MEMBER_D_SK
,'TABLE_B' AS JOIN_TABLE_NAME
,'MEMBER_D_SK' AS HASH_KEY_NAME
, 'TABLE_A' AS Table_Name
,(CASE
WHEN
a.MEMBER_D_SK = z.MEMBER_D_SK THEN "MATCH"
ELSE "FAIL"
END) AS MATCH_TYPE
FROM DATAMART.TABLE_A a
LEFT JOIN (SELECT
DISTINCT MEMBER_D_SK
FROM DATAMART.TABLE_B) z
ON a.MEMBER_D_SK = z.ME

Writing a script to guess foreign keys in Oracle SQL

I am trying to write a SQL script that guesses foreign keys. My approach is to eliminate every column that can't be a foreign key. The rest would be manual work.
SELECT
atc1.table_name atc1_tn,
atc1.column_name atc1_cn,
atc2.table_name atc2_tn,
atc2.column_name atc2_cn
FROM
all_tab_cols atc1,
all_tab_cols atc2
WHERE
atc1.data_type = 'NUMBER'
AND atc1.data_type = atc2.data_type
AND atc1.table_name != atc2.table_name
AND atc1.high_value <= atc2.high_value
AND atc1.num_distinct <= atc2.num_distinct
At this point I get all possible matching columns but that is still not accurate enough.
The next step would be to check if every entry in atc1.column_name exists in atc2.column_name, because if not it can't be a foreign key.
How can I add that condition to my where clause?
The approach is:
Select
(execute immediate 'select '||ATC1_CN||' from '||ATC1_TN||'') as a,
(execute immediate 'select '||ATC2_CN||' from '||ATC2_TN||'') as b
from my_temp_table
where a not in b;
But that doesn't work as expected, because I can't use the table names in a string for a query.
Try the below for existing foreign keys
SELECT a.table_name, a.column_name, a.constraint_name, c.owner,
-- referenced pk
c.r_owner, c_pk.table_name r_table_name, c_pk.constraint_name r_pk
FROM all_cons_columns a
JOIN all_constraints c ON a.owner = c.owner
AND a.constraint_name = c.constraint_name
JOIN all_constraints c_pk ON c.r_owner = c_pk.owner
AND c.r_constraint_name = c_pk.constraint_name
WHERE c.constraint_type = 'R'
For potential foreign keys here are some pointers
The data type of foreign and referenced key should be same
The values in foreign and referenced key columns should be same
The child and parent tables must be on the same database
For query you can use the below
declare
prec number;
begin
for rec in (SELECT atc1.table_name atc1_tn,
atc1.column_name atc1_cn,
atc2.table_name atc2_tn,
atc2.column_name atc2_cn
FROM user_tab_cols atc1, user_tab_cols atc2
WHERE atc1.data_type = 'NUMBER'
AND atc1.data_type = atc2.data_type
AND atc1.table_name != atc2.table_name
AND atc1.high_value <= atc2.high_value
AND atc1.num_distinct <= atc2.num_distinct
) loop
execute immediate 'select count(1) from ' || rec.atc1_tn ||
' a where EXISTS (SELECT 1 FROM ' || rec.atc2_tn ||
' b where a.' || rec.atc1_cn || '!=' || ' b.' ||
rec.atc2_cn || ' )'
into prec;
if prec = 0 Then
dbms_output.put_line('potential foreign key rec:table1 ' ||
rec.atc1_tn || ' table2: ' || rec.atc2_tn ||
' column1: ' || rec.atc1_cn || ' column2: ' ||
rec.atc2_cn);
end if;
end loop;
end;

Find MAX(PK_COLUMN) and display it with corresponding Table Name

I am having 20 tables ( Each table has a PK and data ), i want to find out what is the current MAX(PK) Value for each table.
I Want the result as follows :
TABLE_NAME MAX_VAL
-------------------- ----------
TABELE_A 114
TABELE_B 55
TABELE_C 14
TABELE_D 866
TABELE_3 4552
is there any way to accomplish this or else i have to write 20 times SELECT MAX(PK_COL) FROM TABLE ?
Assuming your currently connected schema is composed of those twenty tables, and each have identical primary key column name(pk_col), then consider the following code block containing an implicit cursor :
declare
v_max pls_integer;
begin
dbms_output.put_line('table_name max_val');
for c in ( select * from user_tables )
loop
execute immediate 'select max(pk_col) from '||c.table_name into v_max;
dbms_output.put_line(c.table_name||' '||v_max);
end loop;
end;
/
i have found another method which will bring TABLE_NAME,PK_COLUMN and MAX( PK_COLUMN ).
SELECT CASE
WHEN RN = 1 THEN
FORMATTED_QUERY_SET
ELSE
FORMATTED_QUERY_SET || ' UNION ALL '
END AS FORMATTED_QUERY_SET
FROM (SELECT ' SELECT NVL(MAX( ' || COL.COLUMN_NAME ||
' ),0) CURR_MAX_VAL, ''' || TAB.TABLE_NAME ||
''' TABLE_NAME,''' || COL.COLUMN_NAME ||
''' COLUMN_NAME FROM ' || TAB.TABLE_NAME AS FORMATTED_QUERY_SET,
TAB.TABLE_NAME,
ROW_NUMBER() OVER(ORDER BY TAB.TABLE_NAME DESC) AS RN
FROM USER_CONSTRAINTS TAB
JOIN USER_CONS_COLUMNS COL
ON TAB.TABLE_NAME = COL.TABLE_NAME
JOIN USER_TAB_COLUMNS COL2
ON COL.COLUMN_NAME = COL2.COLUMN_NAME
AND COL.TABLE_NAME = COL2.TABLE_NAME
WHERE TAB.CONSTRAINT_TYPE = 'P'
AND COL.CONSTRAINT_NAME LIKE '%_PK'
AND REGEXP_LIKE(COL2.DATA_TYPE, ('NUMB|INTE')))
ORDER BY TABLE_NAME;
Copy the output returned by the above query and execute.
Note : Remove the last ' UNION ALL ' operator from the query string.
Note : Please correct me if i am doing anything wrong .

"No Data found" error when compiling PLSQL Function

When trying to compile in order to execute both functions(#directory) I keep getting a no data error on line 48. (or line 13 for the function). This is the error i receive. NOTE: SYSTEM is the server I'm connected to.
ERROR at line 1:
ORA-01403: no data found
ORA-06512: at "SYSTEM.DEPTPROJECT", line 13
ORA-06512: at line 4
ORA-06512: at line 4
these are my function
SET ECHO ON;
SET FEEDBACK ON;
SET LINESIZE 100;
SET PAGESIZE 100;
SET SERVEROUTPUT ON;
CREATE OR REPLACE FUNCTION DEPTPROJECT(departmentNumber IN NUMBER)
RETURN VARCHAR IS
dep# DEPARTMENT.D#%TYPE;
depName DEPARTMENT.DName%TYPE;
counter NUMBER(10,0);
empNumber CHAR(5);
empName VARCHAR2(30);
result VARCHAR2(600);
BEGIN
SELECT D#, DNAME INTO dep#, depName FROM DEPARTMENT WHERE DEPARTMENT.D# = dep#;
result := result || 'Department'|| dep# || '' || depName || chr (10);
FOR i IN(SELECT P# , PTitle , Budget FROM PROJECT WHERE PROJECT.D# = dep# ORDER BY BUDGET DESC)
LOOP
result:= result || chr(9)|| 'Project: ' || i.P# || '' || i.PTitle || i.Budget || chr(10);
FOR j IN(SELECT EMPLOYEE.Name, EMPLOYEE.E# FROM WORKSON INNER JOIN EMPLOYEE ON EMPLOYEE.E# = WORKSON.E# WHERE WORKSON.P# = i.P# ORDER BY EMPLOYEE.NAME ASC )
LOOP
result:= result || chr(10) || j.E# || '' || j.Name || chr(10);
END LOOP;
END LOOP;
RETURN result;
END;
/
BEGIN
FOR x IN(SELECT D# FROM DEPARTMENT)
LOOP
DBMS_OUTPUT.PUT_LINE(DEPTPROJECT(x.D#));
END LOOP;
END;
/
When you are selecting INTO a variable and there are no records returned you should get a NO DATA FOUND error. I believe the correct way to write the above code would be to wrap the SELECT statement with it's own BEGIN/EXCEPTION/END block.
Example:
SET ECHO ON;
SET FEEDBACK ON;
SET LINESIZE 100;
SET PAGESIZE 100;
SET SERVEROUTPUT ON;
CREATE OR REPLACE FUNCTION DEPTPROJECT(departmentNumber IN NUMBER)
RETURN VARCHAR IS
dep# DEPARTMENT.D#%TYPE;
depName DEPARTMENT.DName%TYPE;
counter NUMBER(10,0);
empNumber CHAR(5);
empName VARCHAR2(30);
result VARCHAR2(600);
BEGIN
SELECT D#, DNAME INTO dep#, depName FROM DEPARTMENT WHERE DEPARTMENT.D# = departmentNumber;
result := result || 'Department'|| dep# || '' || depName || chr (10);
FOR i IN(SELECT P# , PTitle , Budget FROM PROJECT WHERE PROJECT.D# = dep# ORDER BY BUDGET DESC)
LOOP
result:= result || chr(9)|| 'Project: ' || i.P# || '' || i.PTitle || i.Budget || chr(10);
FOR j IN(SELECT EMPLOYEE.Name, EMPLOYEE.E# FROM WORKSON INNER JOIN EMPLOYEE ON EMPLOYEE.E# = WORKSON.E# WHERE WORKSON.P# = i.P# ORDER BY EMPLOYEE.NAME ASC )
LOOP
result:= result || chr(10) || j.E# || '' || j.Name || chr(10);
END LOOP;
END LOOP;
EXCEPTION
WHEN NO_DATA_FOUND THEN
result := 'Record Not Found';
RETURN result;
END;
/
BEGIN
FOR x IN(SELECT D# FROM DEPARTMENT)
LOOP
DBMS_OUTPUT.PUT_LINE(DEPTPROJECT(x.D#));
END LOOP;
END;
/
I'd guess that line 13 should use the variable being passed to the function:
SELECT D#, DNAME INTO dep#, depName FROM DEPARTMENT WHERE DEPARTMENT.D# = dep#;
Should be:
SELECT D#, DNAME INTO dep#, depName FROM DEPARTMENT WHERE DEPARTMENT.D# = departmentNumber;
You are using following query to fetch dep# and depName but your where clause is WHERE DEPARTMENT.D# = dep# .
SELECT D#, DNAME INTO dep#, depName FROM DEPARTMENT WHERE DEPARTMENT.D# = dep#;
Here dep# is a variable which you have declared but not initialized.
So dep# is null and comparision to NULL will always lead to false which means your query is returning no record.
As you have used INTO in your query, Oracle is seeking for exactly one record from this query but it is returning no records. Hence, you are facing the issue.
According to your logic either change the WHERE clause to include departmentNumber in comparision or assign proper value to dep# before using it in your query.
Also, make sure to wrap your SELECT .. INTO query in BEGIN..EXCEPTION..END to avoid such a dynamic exception.
Cheers!!

Porting from Oracle to Postgres

Earlier our hosted environments were on Oracle but now we have recently switched to postgres. Porting the tables I believe was successfully since it has been working correct for a long time. I have been actually struggling with porting a procedure but is not working for some reason. I went through the documentation part of the ora2pg but I am not able to crack, which I believe is the last piece of the puzzle.
I've started with this one, which looks like this in Oracle:
create or replace
procedure c_audit(anonymous in boolean, aud_level IN varchar)
AUTHID CURRENT_USER IS
script varchar2(32000);
acc_select varchar(100);
open_cursor integer;
returnval integer;
p_id integer;
a_id integer;
p_name varchar2(100);
a_name varchar2(100);
v_count integer;
c_count integer;
doc_count integer;
curr_user varchar(100);
begin
for i in (select a.a_name a_name, a.a_id, p.name p_name, p.id p_id, ds.username username
from c_account a
inner join c_pro p on a.a_id = p.a_id
inner join c_dat_ds_xref x on p.id = x.p_id
inner join c_data ds on x.id_datasource = ds.id
inner join c_conntypes ct on x.id_conntype = ct.id_conntype
where ct.typeid = 'CAPTURE'
order by a.a_name, p.name)
LOOP
curr_user := i.username;
IF anonymous = true
THEN
acc_select := 'select ' || '''' || i.a_id || '''' || ' a_id,' || '''' || i.p_id || '''' || ' p_id';
ELSE
acc_select := 'select ' || '''' || i.a_name || '''' || ' a_name,' || '''' || i.p_name || '''' || ' p_name';
END IF;
IF upper(aud_level) = 'VERBATIM'
THEN
script:= acc_select || '
, count(distinct d.document_id) docCount
, sum(case when v.document_id is null or v.verbatim_type_value = ''NO_VERBATIM_TEXT'' then 0 else 1 end) VerbCount
, sum(case when v.document_id is null then (select to_number(prop_value) verbSize
from c_properties
where prop_name = ''METERING.STRUCT.ONLY.CHARGE''
and id_pro = 0) else v.credits end) CreditCount
from ' || i.username || '.p_document d
left outer join (
select vi.document_id, t.verbatim_type_value
, case when dbms_lob.substr(vi.extracted_original,8) = ''<cbnull>''
or t.verbatim_type_value = ''NO_VERBATIM_TEXT''
then coalesce(s2.strucCredit, .25)
else ceil(vi.extracted_original_size/coalesce(s.verbSize, 2048)) end credits
from ' || i.username || '.p_verbatim vi
left outer join ' || i.username || '.pd_verbatim_type t on vi.verbatim_type_id = t.verbatim_type_id
, (
select to_number(prop_value) verbSize
from c_properties
where prop_name = ''METERING.MAXSIZE.VERBATIM''
and id_pro = 0
) s
, (
select to_number(prop_value) strucCredit
from c_properties
where prop_name = ''METERING.STRUCT.ONLY.CHARGE''
and id_pro = 0
) s2
) v on d.document_id = v.document_id';
ELSE
IF upper(aud_level) = 'DOCUMENT'
THEN
script:= acc_select || '
, count(distinct a.document_id) docCount
, sum(credits) creditCount
from (
select d.document_id, ceil(sum(v.extracted_original_size)/coalesce(s.verbSize,2048)) credits
from ' || i.username || '.p_document d
inner join ' || i.username || '.p_verbatim v on d.document_id = v.document_id
inner join ' || i.username || '.pd_verbatim_type t on v.verbatim_type_id = t.verbatim_type_id
, (
select to_number(prop_value) verbSize
from c_properties
where prop_name = ''METERING.MAXSIZE.VERBATIM''
and id_pro = 0
) s
where t.verbatim_type_value <> ''NO_VERBATIM_TEXT''
and dbms_lob.substr(v.extracted_original,8) <> ''<cbnull>''
group by d.document_id, s.verbSize
union
select d.document_id, coalesce(s2.strucCredit, .25)
from ' || i.username || '.p_document d
, (
select to_number(prop_value) strucCredit
from c_properties
where prop_name = ''METERING.STRUCT.ONLY.CHARGE''
and id_pro = 0
) s2
where d.document_id not in (select distinct v.document_id from ' || i.username || '.p_verbatim v)
union
select distinct d.document_id, coalesce(s2.strucCredit, .25)
from ' || i.username || '.p_document d
inner join ' || i.username || '.p_verbatim v on d.document_id = v.document_id
inner join ' || i.username || '.pd_verbatim_type t on v.verbatim_type_id = t.verbatim_type_id
, (
select to_number(prop_value) strucCredit
from c_properties
where prop_name = ''METERING.STRUCT.ONLY.CHARGE''
and id_pro = 0
) s2
where (t.verbatim_type_value = ''NO_VERBATIM_TEXT''
or dbms_lob.substr(v.extracted_original,8) = ''<cbnull>'')
) a';
ELSE
dbms_output.put_line('Invalid choice for audit level, no audit generated');
exit;
END IF;
END IF;
begin
open_cursor := dbms_sql.open_cursor;
DBMS_SQL.PARSE(open_cursor, script,
DBMS_SQL.NATIVE);
IF anonymous = true then
dbms_sql.define_column(open_cursor,1,a_id);
dbms_sql.define_column(open_cursor,2,p_id);
else
dbms_sql.define_column(open_cursor,1,a_name,100);
dbms_sql.define_column(open_cursor,2,p_name,100);
end if;
dbms_sql.define_column(open_cursor,3,doc_count);
dbms_sql.define_column(open_cursor,4,v_count);
IF upper(aud_level) = 'VERBATIM' then
dbms_sql.define_column(open_cursor,5,c_count);
end if;
returnval := DBMS_SQL.EXECUTE(open_cursor);
loop
if dbms_sql.fetch_rows(open_cursor) > 0 then
IF anonymous = true then
dbms_sql.column_value(open_cursor,1,a_id);
dbms_sql.column_value(open_cursor,2,p_id);
dbms_sql.column_value(open_cursor,3,doc_count);
dbms_sql.column_value(open_cursor,4,v_count);
IF upper(aud_level) = 'VERBATIM' then
dbms_sql.column_value(open_cursor,5,c_count);
dbms_output.put_line(a_id || ',' || p_id || ',' || doc_count || ',' || v_count || ',' || c_count);
else
dbms_output.put_line(a_id || ',' || p_id || ',' || doc_count || ',' || v_count);
end if;
else
dbms_sql.column_value(open_cursor,1,a_name);
dbms_sql.column_value(open_cursor,2,p_name);
dbms_sql.column_value(open_cursor,3,doc_count);
dbms_sql.column_value(open_cursor,4,v_count);
IF upper(aud_level) = 'VERBATIM' then
dbms_sql.column_value(open_cursor,5,c_count);
dbms_output.put_line(a_name || ',' || p_name || ',' || doc_count || ',' || v_count || ',' || c_count);
else
dbms_output.put_line(a_name || ',' || p_name || ',' || doc_count || ',' || v_count);
end if;
end if;
else
exit;
end if;
end loop;
exception
when others then
--dbms_output.put_line('Error occured. Please check if the current user has Select access to table ' || curr_user || '.p_document ' || curr_user || '.p_verbatim ' || curr_user || '.pd_verbatim_type');
dbms_output.put_line('Error occured. Please login as ' || curr_user || ' and run the following:');
dbms_output.put_line('GRANT SELECT ON ' || curr_user || '.P_DOCUMENT to ' || user ||';');
dbms_output.put_line('GRANT SELECT ON ' || curr_user || '.P_VERBATIM to ' || user ||';');
dbms_output.put_line('GRANT SELECT ON ' || curr_user || '.pd_verbatim_type to ' || user ||';');
end;
end loop;
end;
Does this procedure appears correct with respect to syntax?
CREATE OR REPLACE FUNCTION c_audit(anonymous boolean, aud_level text) RETURNS VOID AS $body$
DECLARE
script text;
acc_select text;
returnval integer;
p_id integer;
a_id integer;
i record;
p_name text;
a_name text;
v_count integer;
c_count integer;
doc_count integer;
curr_user text;
BEGIN
for i in (SELECT a.a_name a_name, a.a_id, p.name p_name, p.id p_id, ds.username username
from c_account a
inner join c_pro p on a.a_id = p.a_id
inner join c_dat_ds_xref x on p.id = x.p_id
inner join c_data ds on x.id_datasource = ds.id
inner join c_conntypes ct on x.id_conntype = ct.id_conntype
where ct.typeid = 'CAPTURE'
order by a.a_name, p.name)
LOOP
curr_user := i.username;
IF anonymous = true
THEN
acc_select := 'SELECT ' || '''' || i.a_id || '''' || ' AccountID,' || '''' || i.p_id || '''' || ' ProjectID';
ELSE
acc_select := 'SELECT ' || '''' || i.a_name || '''' || ' AccountName,' || '''' || i.p_name || '''' || ' ProjectName';
END IF;
IF upper(aud_level) = 'VERBATIM'
THEN
script:= acc_select || '
, count(distinct d.document_id) docCount
, sum(case when coalesce(CAST(v.document_id AS text), '') = '' or v.verbatim_type_value = ''NO_VERBATIM_TEXT'' then 0 else 1 end) VerbCount
, sum(case when coalesce(CAST(v.document_id AS text), '') = '' then (SELECT to_number(prop_value,''9999.99'') verbSize
from c_properties
where prop_name = ''METERING.STRUCT.ONLY.CHARGE''
and id_project = 0) else v.credits end) CreditCount
from ' || i.username || '.p_document d
left outer join (
SELECT vi.document_id, t.verbatim_type_value
, case when substr(vi.extracted_original,8) = ''<cbnull>''
or t.verbatim_type_value = ''NO_VERBATIM_TEXT''
then coalesce(s2.strucCredit, .25)
else ceil(vi.extracted_original_size/coalesce(s.verbSize, 2048)) end credits
from ' || i.username || '.p_verbatim vi
left outer join ' || i.username || '.pd_verbatim_type t on vi.verbatim_type_id = t.verbatim_type_id
, (
select to_number(prop_value,''9999.99'') verbSize
from c_properties
where prop_name = ''METERING.MAXSIZE.VERBATIM''
and id_project = 0
) s
, (
select to_number(prop_value,''9999.99'') strucCredit
from c_properties
where prop_name = ''METERING.STRUCT.ONLY.CHARGE''
and id_project = 0
) s2
) v on d.document_id = v.document_id';
SELECT format(script) into script;
ELSE IF upper(aud_level) = 'DOCUMENT'
THEN
script:= acc_select || '
, count(distinct a.document_id) docCount
, sum(credits) creditCount
from (
SELECT d.document_id, ceil(sum(v.extracted_original_size)/coalesce(s.verbSize,2048)) credits
from ' || i.username || '.p_document d
inner join ' || i.username || '.p_verbatim v on d.document_id = v.document_id
inner join ' || i.username || '.pd_verbatim_type t on v.verbatim_type_id = t.verbatim_type_id
, (
SELECT to_number(prop_value,''9999.99'') verbSize
from c_properties
where prop_name = ''METERING.MAXSIZE.VERBATIM''
and id_project = 0
) s
where t.verbatim_type_value <> ''NO_VERBATIM_TEXT''
and substr(v.extracted_original,8) <> ''<cbnull>''
group by d.document_id, s.verbSize
union
select d.document_id, coalesce(s2.strucCredit, .25)
from ' || i.username || '.p_document d
, (
select to_number(prop_value,''9999.99'') strucCredit
from c_properties
where prop_name = ''METERING.STRUCT.ONLY.CHARGE''
and id_project = 0
) s2
where d.document_id not in (select distinct v.document_id from ' || i.username || '.p_verbatim v)
union
select distinct d.document_id, coalesce(s2.strucCredit, .25)
from ' || i.username || '.p_document d
inner join ' || i.username || '.p_verbatim v on d.document_id = v.document_id
inner join ' || i.username || '.pd_verbatim_type t on v.verbatim_type_id = t.verbatim_type_id
, (
select to_number(prop_value,''9999.99'') strucCredit
from c_properties
where prop_name = ''METERING.STRUCT.ONLY.CHARGE''
and id_project = 0
) s2
where (t.verbatim_type_value = ''NO_VERBATIM_TEXT''
or substr(v.extracted_original,8) = ''<cbnull>'')
) a';
SELECT format(script) into script;
ELSE
SELECT format(script) into script;
exit;
END IF;
END IF;
BEGIN
IF anonymous = true
THEN
IF upper(aud_level) = 'VERBATIM'
THEN
EXECUTE script into a_id, p_id, doc_count, v_count, c_count;
ELSE
EXECUTE script into a_id, p_id, doc_count, c_count;
END IF;
ELSE
IF upper(aud_level) = 'VERBATIM'
THEN
EXECUTE script into a_name, p_name, doc_count, v_count, c_count;
ELSE
EXECUTE script into a_name, p_name, doc_count, c_count;
END IF;
END IF;
GET DIAGNOSTICS returnval := ROW_COUNT;
LOOP
IF returnval > 0
THEN
IF anonymous = true
THEN
IF upper(aud_level) = 'VERBATIM'
THEN
SELECT format ('Information %s, %s, %s, %s, %s', a_id, p_id, doc_count, v_count, c_count);
ELSE
SELECT format ('Information %s, %s, %s, %s', a_id, p_id, doc_count, c_count);
END IF;
ELSE
IF upper(aud_level) = 'VERBATIM'
THEN
SELECT format ('Information %s, %s, %s, %s, %s', a_name, p_name, doc_count, v_count, c_count);
ELSE
SELECT format ('Information %s, %s, %s, %s', a_name, p_name, doc_count, c_count);
END IF;
END IF;
ELSE
EXIT;
END IF;
END LOOP;
EXCEPTION
WHEN others THEN
PERFORM format('Error occured. Please login as %s, %s' , curr_user , ' and run the following:');
PERFORM format('GRANT SELECT ON %s.P_DOCUMENT to %s', curr_user, user);
PERFORM format('GRANT SELECT ON %s.P_VERBATIM to %s', curr_user, user);
PERFORM format('GRANT SELECT ON %s.pd_verbatim_type to %s', curr_user, user);
END;
END LOOP;
END;
$body$
LANGUAGE PLPGSQL
;
ALTER FUNCTION cb_audit(boolean, text) OWNER TO USER;
-- REVOKE ALL ON FUNCTION cb_audit FROM PUBLIC;
The error for failure I get is -
ERROR: too many parameters specified for RAISE
Where: PL/pgSQL function "cb_audit" line 145 at RAISE
I found this to be a good link which I used as a reference
I believe that for porting DBMS_OUTPUT.PUT_LINE, RAISE NOTICE should be the right way. I had encountered another error which was for format of the - to_number(prop_value,'9999.99') which appears right as per the syntax mentioned here but then for some reason when I switched to to_number(prop_value,''9999.99''), I did not get the error but not sure why that should be or even if it should work correctly.
The version of Postgres -
PostgreSQL 9.1.10 on x86_64-unknown-linux-gnu, compiled by gcc (GCC) 4.4.7 20120313 (Red Hat 4.4.7-3), 64-bit
Edited:
I actually attempted to modify this function based on the suggestions from Patrick but due to some reason it is not displaying anything on the screen. I added format() at the end of every script to display the script as but it just executed the code and displays c_audit and null. Though I execute the individual subsql and they do return expected counts and results. Am I missing anything?
You are using two types of string "building": the concatenation || operator and the % placeholder. Both are perfectly legal, but use of the format() function is preferred because the code is cleaner and PG guards against things like SQL-injection behind the scenes.
The error you are getting is that one of your RAISE NOTICE commands has a number of % different from the arguments you supply; forgive me for not looking that up but line 145 is hard to find here on SO. In general, you should rewrite all of them like so:
RAISE NOTICE format('GRANT SELECT ON %I.pd_verbatim_type to %I', curr_user, user);
The %I placeholder takes a SQL identifier as input: it can not be NULL and it will be properly quoted to avoid SQL-injection and keyword collisions. (From your code I take it that curr_user is a schema name and user is a role name, both SQL identifiers.)
Note also that the PERFORM statement in a PL/pgSQL function is a SELECT statement that does not return data, but it is executed to examine a side effect, such as asserting that some data exists. As a consequence, there is no PERFORM privilege, use GRANT SELECT instead.
When quoting in PostgreSQL, SQL-identifiers use double quotes, while string literal values use single quotes. The to_number() function definitely requires single quotes.
A few more points to improve your code:
(1) The two sub-selects in the dynamic query like this one...
'select to_number(prop_value,''9999.99'') strucCredit
from c_properties
where prop_name = ''METERING.STRUCT.ONLY.CHARGE''
and id_project = 0'
... are STABLE: you always get the same result. Instead of leaving them in the dynamic SQL, create two variables and put the results in them before you do anything else:
DECLARE
...
verbSize numeric;
strucCredit numeric;
BEGIN
SELECT to_number(prop_value,'9999.99') INTO verbSize
FROM c_properties
WHERE prop_name = 'METERING.MAXSIZE.VERBATIM' AND id_pro = 0;
SELECT to_number(prop_value,'9999.99') INTO strucCredit
FROM c_properties
WHERE prop_name = 'METERING.STRUCT.ONLY.CHARGE' AND id_pro = 0;
...
Then use the varibale verbSize and strucCredit in your dynamic SQL. Like this you do these queries just once, instead of a few times for every iteration.
(2) All of the dynamic queries need a GROUP BY 1, 2 clause.
(3) The clause CASE WHEN coalesce(CAST(v.document_id AS text), '') = '' ... should be written like CASE WHEN v.document_id IS NULL ..., assuming that v.document_id can not be an empty string.
(4) You changed your RAISE NOTICE statements to SELECT format(...). That latter form produces no output, use RAISE NOTICE format(...) instead.
(5) Rewrite your dynamic SQL to use the format() function too.

Resources