I have 3 input parameters,based on values of each input parameter i have to prepare the SQL in procedure dynamically. I am doing below way but it is failing, if the parameter value is null,then i have to exclude that from the where clause.
IN Parameters:
empid in varchar2 || empname IN varchar2 || empsal IN varchar2
SELECT
EMP_NAME
INTO
V_EMP_NAME
FROM
EMPLOYEE
WHERE
( EMP_ID = EMPID
OR ( EMP_ID IS NULL
AND EMPID IS NULL ) )
AND ( EMP_NAME = EMPNAME
OR ( EMP_NAME IS NULL
AND EMPNAME IS NULL ) )
AND ( EMP_SAL = EMPSAL
OR ( EMP_SAL IS NULL
AND EMPSAL IS NULL ) );
After updates i modified the query like below,it is compiled but giving run time errors saying that ORA-00933: SQL command not properly ended on just before EXECUTE IMMEDIATE
V_SQL :='SELECT EMP_NAME INTO V_empname FROM employee WHERE ';
BEGIN
IF(EMPID IS NOT NULL) THEN
V_SQL := V_SQL || ' emp_id='||EMPID;
END IF;
IF(EMPNAME IS NOT NULL) THEN
V_SQL := V_SQL || ' AND emp_name='||EMPNAME;
END IF;
IF(V_empsalIS NOT NULL) THEN
V_SQL := V_SQL || ' AND emp_sal='||empsal;
V_SQL := V_SQL ||' AND ACTIVE =''Y''' ;
END IF;
EXECUTE IMMEDIATE V_SQL;
EXCEPTION
WHEN NO_DATA_FOUND THEN
V_check:= '' ;
END;
Here you are another alternative:
V_SQL_WHERE := null;
V_SQL :='SELECT EMP_NAME INTO V_empname FROM employee';
BEGIN
IF(EMPID IS NOT NULL) THEN
V_SQL_WHERE := V_SQL_WHERE || ' emp_id='||EMPID;
END IF;
IF(EMPNAME IS NOT NULL) THEN
IF (V_SQL_WHERE is not null) THEN
V_SQL_WHERE := V_SQL_WHERE || ' AND ';
END IF;
V_SQL_WHERE := V_SQL_WHERE || ' emp_name='||EMPNAME;
END IF;
IF(V_empsalIS NOT NULL) THEN
IF (V_SQL_WHERE is not null) THEN
V_SQL_WHERE := V_SQL_WHERE || ' AND ';
END IF;
V_SQL_WHERE := V_SQL_WHERE || ' emp_sal=' || empsal;
V_SQL_WHERE := V_SQL_WHERE || ' AND ACTIVE =''Y''' ;
END IF;
IF (V_SQL_WHERE is not null) then
V_SQL := V_SQL || ' WHERE ' || V_SQL_WHERE;
end if;
EXECUTE IMMEDIATE V_SQL;
EXCEPTION
WHEN NO_DATA_FOUND THEN
V_check:= '' ;
END;
Something like this: (Not tested, but just an idea)
BEGIN
IF EMPID IS NOT NULL
THEN
CLAUSE1 := 'EMP_ID = EMPID';
ELSE
CLAUSE1 := '1=1';
END IF;
IF EMPNAME IS NOT NULL
THEN
CLAUSE2 := 'EMP_NAME = EMPNAME';
ELSE
CLAUSE2 := '1=1';
END IF;
IF EMPSAL IS NOT NULL
THEN
CLAUSE3 := 'EMP_SAL = EMPSAL';
ELSE
CLAUSE3 := '1=1';
END IF;
IF ( EMPSAL IS NULL
AND EMPNAME IS NULL
AND EMPID IS NOT NULL )
THEN
CLAUSE1 := '1=0';
CLAUSE2 := '1=0';
CLAUSE3 := '1=0';
END IF;
QUERY_STR :=
' SELECT EMP_NAME INTO V_EMP_NAME FROM EMPLOYEE WHERE'
|| CLAUSE1
|| ' AND '
|| CLAUSE2
|| ' AND '
|| CLAUSE3;
END;
You can create one from scratch, including if's and elses, or you can use a package called plsql-utils, the SQL_BUILDER_PKG. It does the whole work for you.
Have a look on SQL utilities
http://code.google.com/p/plsql-utils/
Eg:
declare
l_my_query sql_builder_pkg.t_query;
l_sql varchar2(32000);
begin
sql_builder_pkg.add_select (l_my_query, 'ename');
sql_builder_pkg.add_select (l_my_query, 'sal');
sql_builder_pkg.add_select (l_my_query, 'deptno');
sql_builder_pkg.add_from (l_my_query, 'emp');
sql_builder_pkg.add_where (l_my_query, 'ename = :p_ename');
sql_builder_pkg.add_where (l_my_query, 'sal > :p_sal');
l_sql := sql_builder_pkg.get_sql (l_my_query);
dbms_output.put_line (l_sql);
end;
I used it in one project and it was a good tool.
Related
I have a oracle stored procedure, inputs is
p_processId = 5660
p_featureClassName ='future_parcels'
p_DrawnGeometry = MDSYS.SDO_GEOMETRY(2003, 2400000, null,
MDSYS.SDO_ELEM_INFO_ARRAY(1, 1003, 1, 27, 2003, 1),
MDSYS.SDO_ORDINATE_ARRAY(8439212.4589933194220066070556640625,
4540074.1191380098462104797363281250, 8439201.7998965308070182800292968750, 4540058.374383729882538318634033203125, 8439315.814959609881043434143066406250, 4540058.374466760084033012390136718750, 8439319.9868115298449993133544921875, 4540067.6362674199044704437255859375, 8439323.231370599940419197082519531250, 4540081.528450479730963706970214843750, 8439328.328618479892611503601074218750, 4540097.737373660318553447723388671875, 8439330.6458750404417514801025390625, 4540129.691041340120136737823486328125, 8439332.959363190457224845886230468750, 4540149.486472180113196372985839843750, 8439227.984901839867234230041503906250, 4540148.055711519904434680938720703125, 8439225.43722324073314666748046875, 4540138.489620880223810672760009765625, 8439223.1199580393731594085693359375, 4540118.576599569991230964660644531250, 8439220.802692830562591552734375, 4540098.663578259758651256561279296875, 8439212.4589933194220066070556640625, 4540074.1191380098462104797363281250, 8439252.6796298995614051818847656250, 4540086.660427900031208992004394531250, 8439243.2996299006044864654541015625, 4540125.440427900291979312896728515625, 8439299.99962989985942840576171875, 4540138.040427899919450283050537109375, 8439310.49962989985942840576171875, 4540098.280427900142967700958251953125, 8439252.6796298995614051818847656250, 4540086.660427900031208992004394531250))
Procedure:
CREATE OR REPLACE
PROCEDURE get_DrawnGeometries (
p_processId IN INTEGER
, p_featureClassName IN VARCHAR2
, p_DrawnGeometry IN SDO_GEOMETRY
, p_prm_val OUT VARCHAR2
)
IS
PRAGMA AUTONOMOUS_TRANSACTION;
CURSOR featClassAttributes_cur (featureClassName IN VARCHAR2) IS
SELECT
gac.id
, lower(gac.column_name) AS column_name
, gac.view_u_pk
, gac.data_type
, gas.naziv
, gat.table_name
FROM geo_atrib_columns gac
JOIN geo_atrib_tables gat ON gat.table_name = gac.table_name
JOIN geo_app_slojevi gas ON gas.naziv = gat.layer_name
WHERE gas.naziv = featureClassName
AND gat.aktivan = 1
AND gac.aktivan = 1
AND gac.view_iu_write = 1
ORDER BY gac.view_order;
vc_sql CLOB;
vc_sql2 CLOB;
vc_sql3 CLOB;
v_columns VARCHAR2(1000);
v_tableName VARCHAR2(1000);
v_whereClause VARCHAR2(1000);
v_whereClause2 VARCHAR2(1000);
v_g_col_name VARCHAR2(30);
v_tolerance VARCHAR2(20);
v_separator VARCHAR2(16) := ' || ''' || glob_var.v_strSeparator || ''' || ';
p_id INTEGER;
v_mssg VARCHAR2(500) := NULL;
BEGIN
vc_sql := 'SELECT #columns# FROM #table_name# WHERE #where_clause#';
vc_sql2 := 'SELECT #columns# FROM #table_name# WHERE #where_clause2#';
vc_sql3 := vc_sql;
FOR rt_att IN featClassAttributes_cur(p_featureClassName) LOOP
IF rt_att.data_type = 'N' THEN
v_columns := v_columns || v_separator || ' nvl(gt_util.num2CharPointSep(' || rt_att.column_name|| '), ''NULL'')';
ELSE
v_columns := v_columns || v_separator || ' nvl(to_char(' || rt_att.column_name|| '), ''NULL'')';
END IF;
IF v_tableName IS NULL THEN
v_tableName := rt_att.table_name;
END IF;
--dbms_output.put_line(v_tableName);
END LOOP;
v_columns := ltrim(v_columns, v_separator);
v_g_col_name := gt_util.get_layer_g_col(v_tableName);
v_tolerance := gt_util.num2CharPointSep(gt_util.get_layer_tollerance(v_tableName, v_g_col_name));
--v_whereClause := 'ins_id = {0} AND SDO_GEOM.RELATE(:geom, ''EQUAL+INSIDE+CONTAINS+COVEREDBY+COVERS+OVERLAPBDYINTERSECT'', ' || v_g_col_name || ', ' || v_tolerance || ') = ''EQUAL+INSIDE+CONTAINS+COVEREDBY+COVERS+OVERLAPBDYINTERSECT''';
v_whereClause := 'ins_id = {0} AND SDO_GEOM.RELATE(:geom, ''EQUAL'', ' || v_g_col_name || ', ' || v_tolerance || ') = ''EQUAL''';
v_whereClause2 := 'ins_id = {0} AND gt_util.geom_is_equal(:geom, ' || v_g_col_name || ', ' || v_tolerance || ') = ''TRUE''';
v_whereClause := replace(v_whereClause, '{0}', to_char(p_processId));
v_whereClause2 := replace(v_whereClause2, '{0}', to_char(p_processId));
vc_sql := replace(vc_sql, '#columns#', v_columns);
vc_sql := replace(vc_sql, '#table_name#', v_tableName);
vc_sql := replace(vc_sql, '#where_clause#', v_whereClause);
vc_sql2 := replace(vc_sql2, '#columns#', v_columns);
vc_sql2 := replace(vc_sql2, '#table_name#', v_tableName);
vc_sql2 := replace(vc_sql2, '#where_clause2#', v_whereClause2);
dbms_output.put_line(vc_sql);
dbms_output.put_line(vc_sql2);
BEGIN
EXECUTE IMMEDIATE vc_sql INTO p_prm_val USING p_DrawnGeometry;
EXCEPTION WHEN NO_DATA_FOUND THEN
EXECUTE IMMEDIATE vc_sql2 INTO p_prm_val USING p_DrawnGeometry;
WHEN TOO_MANY_ROWS THEN
vc_sql3 := replace(vc_sql3, '#columns#', 'id');
vc_sql3 := replace(vc_sql3, '#table_name#', v_tableName);
vc_sql3 := replace(vc_sql3, '#where_clause#', v_whereClause);
vc_sql3 := 'SELECT * FROM (' || vc_sql3 || ' ORDER BY id DESC) WHERE ROWNUM = 1';
EXECUTE IMMEDIATE vc_sql3 INTO p_id USING p_DrawnGeometry;
EXECUTE IMMEDIATE 'DELETE FROM ' || v_tableName || ' WHERE id = ' || p_id;
COMMIT;
v_mssg := 'Identical geometry already exists. Drawn geometry is deleted. If you want to delete new geometry please delete the old one first';
RAISE error_util.ep_UsrExc;
--dbms_output.put_line(vc_sql2);
END;
EXCEPTION WHEN error_util.ep_UsrExc THEN
ERROR_UTIL.log_and_raise(SQLCODE, SQLERRM, v_mssg, DBMS_UTILITY.FORMAT_ERROR_BACKTRACE);
RAISE;
END get_DrawnGeometries;
how I can check result and debug it output ?
when I can call it returned errors
Procedure execution failed ORA-06550: line 1, column 233: PLS-00382:
expression is of wrong type ORA-06550: line 1, column 213: PL/SQL:
Statement ignored
In PL/SQL Developer you can right click on procedure name, click test and start debbuging
I need to check the parameters in the stored procedure if it is entered then I need to select that
i=j=k=l=m=1;
IF (p_plant_cd IS NULL) THEN
i=0;
END IF;
IF(p_global_duns_nbr IS NULL) THEN
j=0
END IF;
IF(p_global_duns_nbr IS NULL) THEN
k=0
END IF;
IF(p_matrl_grp IS NULL) THEN
l=0
END IF;
IF (p_mrp IS NULL) THEN
m=0
END IF ;
Which ever value is 1 I need to add corresponding parameters in the variable v_select
For eg ;
if k and l are 1 then
v_select='p_global_duns_nbr,p_matrl_grp'
Pls suggest me how to do this.
You can declare a variable , holding column names , then concat to select statement and you have SQL select statement in v_select , use it as you want
declare
v_columns varchar2(255);
v_select varchar2(2000);
v_result sys_refcursor;
begin
v_columns := 'rownum';
IF p_plant_cd = 1 THEN
v_columns := v_columns || ',p_plant_cd';
END IF;
IF p_global_duns_nbr = 1 THEN
v_columns := v_columns || ',p_global_duns_nbr';
END IF;
IF p_global_duns_nbr = 1 THEN
v_columns := v_columns || ',p_global_duns_nbr';
END IF;
IF p_matrl_grp = 1 THEN
v_columns := v_columns || ',p_matrl_grp';
END IF;
IF p_mrp = 1 THEN
v_columns := v_columns || ',p_mrp';
END IF;
v_select := 'SELECT ' || v_columns || ' FROM table';
open v_result for v_select;
end;
I have written foll query but getting error:
PLS-00103: Encountered the symbol "end-of-file" when expecting one of the following:
:= . ( # % ;
Following is the stored procedure query
I know its the syntax error but cannot figure out where exactly the problem is.
It will be a great help if someone help me.
CREATE OR REPLACE PROCEDURE MCSIL_HR.sp_ins_emp_mst_DEV (
inemp_id emp_mst.emp_id%TYPE,
inemp_restrict_emp emp_mst.restrict_emp%TYPE,
inemp_name emp_mst.emp_name%TYPE,
inemp_email emp_mst.email_id%TYPE,
inemp_pwd emp_mst.emp_pwd%TYPE,
indob VARCHAR2,
indoj VARCHAR2,
indor VARCHAR2,
inemp_status_lkp_id emp_mst.emp_status_lkp_id%TYPE,
inemp_has_reportee_status emp_mst.has_reportees_status_yn%TYPE,
inupd_emp_id emp_mst.emp_id%TYPE,
inupd_flag CHAR,
indept VARCHAR2,
inmgr_id emp_mst.mgr_id%TYPE,
outmsg OUT VARCHAR2,
outstatus OUT VARCHAR2
)
IS
pgm_error EXCEPTION;
as_emp_id emp_mst.emp_id%TYPE;
as_cnt NUMBER;
upd_flag VARCHAR2 (3);
asdob DATE;
asdoj DATE;
asdor DATE;
BEGIN
outmsg := '';
outstatus := 'TRUE';
upd_flag := UPPER (TRIM (inupd_flag));
-- check if Emp Status lookup value exists in lookup table , if not raise error
SELECT COUNT (1)
INTO as_cnt
FROM lookup l
WHERE l.lkp_id = inemp_status_lkp_id;
IF as_cnt = 0
THEN
outmsg :=
'Employee Sattus LOOK UP VALUE : '
|| TO_CHAR (inemp_status_lkp_id)
|| ' NOT EXISTS IN LOOKUP TABLE ';
outstatus := 'INSERT/UPDATE/DELETE Failed.';
RAISE pgm_error;
END IF;
-- check if Yes/No Status ookup value exists in lookup table , if not raise error
SELECT COUNT (1)
INTO as_cnt
FROM lookup l
WHERE l.lkp_id = inemp_has_reportee_status;
IF as_cnt = 0
THEN
outmsg :=
'Has_Reportees Status LOOK UP VALUE : '
|| TO_CHAR (inemp_has_reportee_status)
|| ' NOT EXISTS IN LOOKUP TABLE ';
outstatus := 'INSERT/UPDATE/DELETE Failed.';
RAISE pgm_error;
END IF;
-- check whether user modifying data is valid employee
SELECT COUNT (1)
INTO as_cnt
FROM emp_mst e
WHERE e.emp_id = inupd_emp_id;
IF as_cnt = 0
THEN
outmsg :=
'UPDATING USER ID: '
|| TO_CHAR (inupd_emp_id)
|| ' NOT EXISTS IN EMPLOYEE MASTER ';
outstatus := 'INSERT/UPDATE/DELETE Failed.';
RAISE pgm_error;
END IF;
-- checking date formatt (dd-mm-yyyy)
IF indob IS NULL
OR NOT ( SUBSTR (TRIM (indob), 3, 1) = '-'
AND SUBSTR (TRIM (indob), 6, 1) = '-'
)
THEN
outmsg :=
'Date of Birth is Blank or Formatt for Date of Birth is not in DD-MM-YYYY, Contact Administrator';
outstatus := 'INSERT/UPDATE/DELETE Failed.';
RAISE pgm_error;
END IF;
IF indoj IS NULL
OR NOT ( SUBSTR (TRIM (indoj), 3, 1) = '-'
AND SUBSTR (TRIM (indoj), 6, 1) = '-'
)
THEN
outmsg :=
'Date of Join is Blank or Formatt for Date of Join is not in DD-MM-YYYY, Contact Administrator';
outstatus := 'INSERT/UPDATE/DELETE Failed.';
RAISE pgm_error;
END IF;
IF indor IS NOT NULL
AND NOT ( SUBSTR (TRIM (indor), 3, 1) = '-'
AND SUBSTR (TRIM (indor), 6, 1) = '-'
)
THEN
outmsg :=
'Formatt for Date of Resign is not in DD-MM-YYYY, Contact Administrator';
outstatus := 'INSERT/UPDATE/DELETE Failed.';
RAISE pgm_error;
END IF;
asdob := TO_DATE (TRIM (indob), 'DD-MM-YYYY');
asdoj := TO_DATE (TRIM (indoj), 'DD-MM-YYYY');
asdor := TO_DATE (TRIM (indor), 'DD-MM-YYYY');
DBMS_OUTPUT.put_line ( 'LKP SRNO, UPDATE USER EMPCODE OK,'
|| 'DOB :'
|| TO_CHAR (asdob)
|| ',DOJ :'
|| TO_CHAR (asdoj)
|| ',DOR :'
|| TO_CHAR (asdor)
);
-- check whether user modifying data is valid employee
SELECT COUNT (*)
INTO as_cnt
FROM emp_mst e
WHERE e.emp_id = inemp_id;
IF upd_flag = 'U'
THEN
IF as_cnt = 0
THEN
outmsg :=
'EMPLOYEE CODE : '
|| TO_CHAR (inemp_id)
|| ' NOT EXISTS IN EMPLOYEE MASTER';
outstatus := 'UPDATE Failed.';
RAISE pgm_error;
END IF;
UPDATE emp_mst a
SET a.rec_dtl = rec_dtl (NULL, NULL, NULL, NULL)
WHERE a.rec_dtl IS NULL;
-- For password change call another procedure
UPDATE emp_mst a
SET a.emp_name = inemp_name,
a.restrict_emp = inemp_restrict_emp,
a.email_id=inemp_email,
a.emp_pwd = ENCRYPT(inemp_pwd),
a.dob = asdob,
a.doj = asdoj,
a.dor = asdor,
a.emp_status_lkp_id = inemp_status_lkp_id,
a.has_reportees_status_yn = inemp_has_reportee_status,
a.rec_dtl.updated_by = inupd_emp_id,
a.DEPT= indept,
a.MGR_ID = inmgr_id,
a.rec_dtl.updated_on = SYSDATE
WHERE a.emp_id = inemp_id;
IF SQLCODE <> 0
THEN
ROLLBACK;
outstatus := 'FALSE';
outmsg := 'UPDATE Failed.';
RAISE pgm_error;
ELSE
COMMIT;
outstatus := 'TRUE';
outmsg := 'Process sucessfully executed';
END IF;
ELSIF upd_flag = 'I'
THEN
IF as_cnt > 0
THEN
outmsg :=
'EMPLOYEE ID : '
|| TO_CHAR (inemp_id)
|| ' ALREADY IN EMPLOYEE MASTER';
outstatus := 'INSERT Failed.';
RAISE pgm_error;
END IF;
INSERT INTO mcsil_hr.emp_mst
(emp_id,restrict_emp, emp_name,email_id, emp_pwd, dob, doj, dor, ---added by shailesh
emp_status_lkp_id, has_reportees_status_yn,
rec_dtl,DEPT,MGR_ID
)
VALUES (inemp_id,inemp_restrict_emp, inemp_name, inemp_email, ENCRYPT(inemp_pwd), asdob, asdoj, asdor, ---added by shailesh
inemp_status_lkp_id, inemp_has_reportee_status,
rec_dtl (inupd_emp_id, SYSDATE, NULL, NULL),indept,inmgr_id
);
IF SQLCODE <> 0
THEN
ROLLBACK;
outstatus := 'FALSE';
outmsg := 'INSERT Failed.';
RAISE pgm_error;
ELSE
COMMIT;
outstatus := 'TRUE';
outmsg := 'Process Sucessfully executed';
END IF;
ELSIF upd_flag = 'D'
THEN
IF as_cnt = 0
THEN
outmsg :=
'EMPLOYEE ID : '
|| TO_CHAR (inemp_id)
|| ' NOT EXISTS IN EMPLOYEE MASTER';
outstatus := 'DELETE Failed.';
RAISE pgm_error;
END IF;
UPDATE emp_mst a
SET a.rec_dtl = rec_dtl (NULL, NULL, NULL, NULL)
WHERE a.rec_dtl IS NULL;
UPDATE emp_mst a
SET a.emp_status_lkp_id = 202, -- INCATIVE ACCOUNT CODE
a.rec_dtl.updated_by = inupd_emp_id,
a.rec_dtl.updated_on = SYSDATE
WHERE a.emp_id = inemp_id;
IF SQLCODE <> 0
THEN
ROLLBACK;
outstatus := 'FALSE';
outmsg := 'DELTE Failed.';
RAISE pgm_error;
ELSE
COMMIT;
outstatus := 'TRUE';
outmsg := 'Process sucessfully executed';
END IF;
ELSE
outstatus := 'FALSE';
outmsg := 'ACTION FLAG SHOULD BE IN I(Insert)/U(Update)/D(Delete).';
RAISE pgm_error;
END IF;
DBMS_OUTPUT.put_line ('STATUS :' || outstatus || ', MGS :' || outmsg);
EXCEPTION
WHEN pgm_error
THEN
BEGIN
outstatus := 'FALSE';
DBMS_OUTPUT.put_line ('STATUS :' || outstatus || ', MGS :' || outmsg);
raise_application_error (-20999, outmsg);
END;
WHEN NO_DATA_FOUND
THEN
BEGIN
outmsg := 'INSERT/UPDATE/DELETE FAILED. NO DATA FOUND';
outstatus := 'FALSE';
DBMS_OUTPUT.put_line ('STATUS :' || outstatus || ', MGS :' || outmsg);
raise_application_error (-20999, outmsg);
END;
WHEN OTHERS
THEN
BEGIN
outmsg := 'INSERT/UPDATE/DELETE FAILED. ';
outstatus := 'FALSE';
DBMS_OUTPUT.put_line ('STATUS :' || outstatus || ', MGS :' || outmsg);
raise_application_error (-20999, outmsg || SQLERRM);
END;
END sp_ins_emp_mst_DEV ;
/
Are you using SQL*Plus? If you are, then it's probably the blank lines in your code, which would be interpreted as the end of a line.
I would suggest you do this:
set echo on
spool sp_ins_emp_mst_dev.log
<your procedure declaration>
spool off
And look very carefully at your line numbers. If they don't run smoothly from the beginning to the end, try making the blank lines into comments (my choice) or set sqlblanklines on.
The output from the below code is:
|LAT|MISC|SID|NO
MIN_LENGTH|1|2|1|1
MAX_LENGTH|6|6|4|2
The output is as I expect, but is there anyway to loop through the columns using an index (ie. j) instead of doing RESULTS(I).MAX_LENGTH , RESULTS(I).MAX_LENGTH etc ? The concern is that when adding extra columns to the 'R_RESULT_REC' record, another loop is required.
set serveroutput on
DECLARE
TYPE R_RESULT_REC IS RECORD
(COL_NAME VARCHAR2(100),
MIN_LENGTH NUMBER,
MAX_LENGTH NUMBER
);
TYPE tr_RESULT IS TABLE OF R_RESULT_REC;
RESULTS TR_RESULT := TR_RESULT();
v_counter NUMBER := 1;
BEGIN
FOR J IN (SELECT DISTINCT COLUMN_NAME FROM ALL_TAB_COLUMNS
WHERE OWNER = 'SYSTEM'
and TABLE_NAME = 'SPECCHAR')
LOOP
RESULTS.EXTEND;
RESULTS(V_COUNTER).COL_NAME := J.COLUMN_NAME;
EXECUTE IMMEDIATE 'SELECT MIN(LENGTH('||J.COLUMN_NAME||')),
MAX(LENGTH('||J.COLUMN_NAME||'))
FROM '||'SYSTEM'||'.'||'SPECCHAR' INTO
RESULTS(V_COUNTER).MIN_LENGTH,
RESULTS(V_COUNTER).MAX_LENGTH;
V_COUNTER := V_COUNTER + 1;
END LOOP;
FOR I IN RESULTS.FIRST .. RESULTS.LAST LOOP
IF I = RESULTS.LAST THEN
DBMS_OUTPUT.PUT_LINE(RESULTS(I).COL_NAME);
ELSIF I = RESULTS.FIRST THEN
DBMS_OUTPUT.PUT(' |'||RESULTS(I).COL_NAME||'|');
ELSE
DBMS_OUTPUT.PUT(RESULTS(I).COL_NAME||'|');
END IF ;
END LOOP;
FOR I IN RESULTS.FIRST .. RESULTS.LAST LOOP
IF I = RESULTS.LAST THEN
DBMS_OUTPUT.PUT_LINE(RESULTS(I).MIN_LENGTH);
ELSIF I = RESULTS.FIRST THEN
DBMS_OUTPUT.PUT('MIN_LENGTH|'||RESULTS(I).MIN_LENGTH||'|');
ELSE
DBMS_OUTPUT.PUT(RESULTS(I).MIN_LENGTH||'|');
END IF ;
END LOOP;
FOR I IN RESULTS.FIRST .. RESULTS.LAST LOOP
IF I = RESULTS.LAST THEN
DBMS_OUTPUT.PUT_LINE(RESULTS(I).MAX_LENGTH);
ELSIF I = RESULTS.FIRST THEN
DBMS_OUTPUT.PUT('MAX_LENGTH|'||RESULTS(I).MAX_LENGTH||'|');
ELSE
DBMS_OUTPUT.PUT(RESULTS(I).MAX_LENGTH||'|');
END IF ;
END LOOP;
end;
This uses DBMS_SQL, so it's pretty snarly to read. The main reason I saw to use it was that I could get columnar descriptions of a SQL statement and to a buffer-based, not object-based fetch.
Rather than making calls to DBMS_OUTPUT during the processing, it builds a table of records for output, using associative arrays for simplicity.
It could further be refined to have an array or parsable list of functions to apply to each function, but that seems excess to current requirements. The nature of the code would require editing if new aggregation functions are being added.
Call overview (2c + a + s):
3 loops;
2 loops over column list (c),
1 loop over number of analytic functions (a).
1 SQL statement against table data (s).
OP's call overview (c*s + a + 1):
1 loop, executing a sql statement against table data per column (c*s)
a+1 loops, where a is the number of analytic functions
Test data:
1 select min(length(GP_ID)), max(length(GP_ID)),
2 min(length(GGP_ID)), max(length(GGP_ID)),
3 min(length(OBJECT_NAME)), max(length(OBJECT_NAME))
4* from AMUSCH.GP
SQL> /
MIN(LENGTH(GP_ID)) MAX(LENGTH(GP_ID)) MIN(LENGTH(GGP_ID))
MAX(LENGTH(GGP_ID)) MIN(LENGTH(OBJECT_NAME)) MAX(LENGTH(OBJECT_NAME))
1 7 1
4 9 41
Code:
declare
p_owner varchar2(30);
p_table_name varchar2(30);
TYPE OUTPUT_TAB_TYPE IS TABLE OF VARCHAR2(32767) index by binary_integer;
OUTPUT_TAB OUTPUT_TAB_TYPE;
l_columns_tab dbms_sql.desc_tab;
l_columns_cur integer;
l_columns_sql varchar2(32767);
l_columns_cnt number;
l_minmax_sql varchar2(32767);
l_minmax_cur integer;
l_minmax_tab dbms_sql.desc_tab;
l_minmax_cnt number;
l_fetch_ok number;
l_fetch_value number;
begin
p_owner := 'AMUSCH';
p_table_name := 'GP';
output_tab(1) := lpad(' ', 20, ' ');
output_tab(2) := lpad('MIN_LENGTH', 20, ' ');
output_tab(3) := lpad('MAX_LENGTH', 20, ' ');
l_columns_sql := 'select * from ' || p_owner || '.' || p_table_name ||
' where 1 = 0';
l_columns_cur := dbms_sql.open_cursor;
dbms_sql.parse (l_columns_cur, l_columns_sql, dbms_sql.native);
dbms_sql.describe_columns (l_columns_cur, l_columns_cnt, l_columns_tab);
-- build the min/max sql statement
l_minmax_sql := 'select ' ;
for i in 1..l_columns_cnt
loop
l_minmax_sql := l_minmax_sql ||
' min(length(' || l_columns_tab(i).col_name || ')), ';
l_minmax_sql := l_minmax_sql ||
' max(length(' || l_columns_tab(i).col_name || ')), ';
end loop;
l_minmax_sql := substr(l_minmax_sql, 1,
length(l_minmax_sql) - 2); -- trim trailing comma
l_minmax_sql := l_minmax_sql || ' from ' || p_owner || '.' || p_table_name;
l_minmax_cur := dbms_sql.open_cursor;
dbms_sql.parse (l_minmax_cur, l_minmax_sql, dbms_sql.native);
dbms_sql.describe_columns (l_minmax_cur, l_minmax_cnt, l_minmax_tab);
for i in 1..l_minmax_cnt
loop
dbms_sql.define_column(l_minmax_cur, i, l_fetch_value);
end loop;
l_fetch_ok := dbms_sql.execute(l_minmax_cur);
loop
l_fetch_ok := dbms_sql.fetch_rows(l_minmax_cur);
exit when l_fetch_ok = 0;
-- loop over the columns selected over
for i in 1..l_columns_cnt
loop
output_tab(1) := output_tab(1) || '|' || l_columns_tab(i).col_name;
dbms_sql.column_value(l_minmax_cur, (2*i-1), l_fetch_value);
output_tab(2) := output_tab(2) || '|' ||
lpad(l_fetch_value, length(l_columns_tab(i).col_name), ' ');
dbms_sql.column_value(l_minmax_cur, (2*i), l_fetch_value);
output_tab(3) := output_tab(3) || '|' ||
lpad(l_fetch_value, length(l_columns_tab(i).col_name), ' ');
end loop;
end loop;
if dbms_sql.is_open(l_minmax_cur) then
dbms_sql.close_cursor (l_minmax_cur);
end if;
if dbms_sql.is_open (l_columns_cur) then
dbms_sql.close_cursor (l_columns_cur);
end if;
for i in output_tab.first..output_tab.last
loop
dbms_output.put_line(output_tab(i));
end loop;
end;
/
Results:
|GP_ID|GGP_ID|OBJECT_NAME
MIN_LENGTH| 1| 1| 9
MAX_LENGTH| 7| 4| 41
If you want to use the DBMS_SQL package (which is sometimes very complex), then there is a DBMS_SQL.COLUMN_VALUE function that may work for you.
update:
Or even better: DBMS_SQL.DESC_REC
you can refer to:
http://docs.oracle.com/cd/B19306_01/appdev.102/b14258/d_sql.htm#i996963
notice example 8
I haven't tested it
update:
Perhaps what you really want is to loop on an Object type attributes and not a table column, so maybe you should try a different approach:
Make your type R_RESULT_REC an Object type in the DB and then you can loop on the query results:
SELECT attr_name
FROM user_type_attrs
WHERE type_name = 'R_RESULT_REC'
It's not like working with indexes but you still don't need to hard code the column names / type attributes
here is the code (based on yours):
CREATE OR REPLACE TYPE R_RESULT_REC AS OBJECT
(
COL_NAME VARCHAR2(100),
MIN_LENGTH NUMBER,
MAX_LENGTH NUMBER
);
/
and then:
DECLARE
TYPE tr_RESULT IS TABLE OF R_RESULT_REC;
RESULTS TR_RESULT := TR_RESULT();
v_counter NUMBER := 1;
v_max number;
v_min number;
BEGIN
FOR J IN (SELECT DISTINCT COLUMN_NAME
FROM ALL_TAB_COLUMNS
WHERE OWNER = 'SYSTEM'
and TABLE_NAME = 'SPECCHAR') LOOP
EXECUTE IMMEDIATE 'SELECT MIN(LENGTH(' || J.COLUMN_NAME || ')),
MAX(LENGTH(' || J.COLUMN_NAME || ')) FROM ' ||
'SPECCHAR'
INTO v_min, v_max;
RESULTS.EXTEND;
RESULTS(V_COUNTER) := new R_RESULT_REC(J.COLUMN_NAME, v_min, v_max);
V_COUNTER := V_COUNTER + 1;
END LOOP;
for r in (select attr_name
from all_type_attrs t
where t.owner = 'SYSTEM'
and t.type_name = 'R_RESULT_REC') loop
FOR I IN RESULTS.FIRST .. RESULTS.LAST LOOP
IF I = RESULTS.LAST THEN
execute immediate 'declare rec R_RESULT_REC := :0; begin' ||
' DBMS_OUTPUT.PUT_LINE(rec.' || r.attr_name || ');' ||
'end;'
using RESULTS(I);
ELSIF I = RESULTS.FIRST THEN
execute immediate 'declare rec R_RESULT_REC := :0; begin' ||
' DBMS_OUTPUT.PUT(''' || r.attr_name ||
'|'' || rec.' || r.attr_name || ' || ''|'');' ||
'end;'
using RESULTS(I);
ELSE
execute immediate 'declare rec R_RESULT_REC := :0; begin' ||
' DBMS_OUTPUT.PUT(rec.' || r.attr_name ||
' || ''|''); ' || 'end;'
using RESULTS(I);
END IF;
END LOOP;
end loop;
end;
If you'll add another attribute to the Record (and initiate it with values) , it will automatic display it.
Take advantage of Oracle's stats for this.
First, fully build stats on table using dbms_stats.gather_table_stats
Then, create the following function to help translate the raw low/high values that Oracle stores in all_tab_columns
create or replace function show_raw(i_raw raw, i_type varchar2)
return varchar2 is
l_varchar2 varchar2(32);
l_number number;
l_date date;
l_nvarchar2 nvarchar2(32);
l_rowid rowid;
l_char char;
begin
if (i_type = 'VARCHAR2') then
DBMS_STATS.CONVERT_RAW_VALUE(i_raw, l_varchar2);
return to_char(l_varchar2);
elsif(i_type = 'NUMBER') then
DBMS_STATS.CONVERT_RAW_VALUE(i_raw, l_number);
return to_char(l_number);
elsif(i_type = 'DATE') then
DBMS_STATS.CONVERT_RAW_VALUE(i_raw, l_date);
return to_char(l_date);
elsif(i_type = 'NVARCHAR2') then
DBMS_STATS.CONVERT_RAW_VALUE(i_raw, l_nvarchar2);
return to_char(l_nvarchar2);
elsif(i_type = 'ROWID') then
DBMS_STATS.CONVERT_RAW_VALUE(i_raw, l_rowid);
return to_char(l_rowid);
elsif(i_type = 'CHAR') then
DBMS_STATS.CONVERT_RAW_VALUE(i_raw, l_char);
return l_char;
else return 'Unknown type value';
end if;
end;
Then, just select the low/high values for each column:
select column_id,
column_name,
data_type,
show_raw(low_value, data_type) as min_val,
show_raw(high_value, data_type) as max_val
from all_tab_columns
where table_name = 'SOME_TABLE'
and owner = 'SOME_OWNER'
;
I am trying to create some dynamic sql using the following code block
firstSqlStatement := true;
updateText := 'UPDATE T_EMPLOYEES SET ';
if FIRSTNAME IS NOT NULL and FIRSTNAME > 0 THEN
updateText:=updateText || ' firstName=' || FIRSTNAME || ' ';
firstSqlStatement := false;
end if;
if MIDDLENAME IS NOT NULL and length(MIDDLENAME) > 0 THEN
if firstSqlStatement = false THEN
updateText:=updateText || ',';
end if;
updateText:=updateText || ' middleName=' || MIDDLENAME || ' ';
firstSqlStatement := false;
end if;
updateText:=updateText
|| ' where upper(id)=upper(' || ID ||');';
DBMS_OUTPUT.put_line(updateText);
EXECUTE IMMEDIATE updateText;
The statement never executes properly as there are missing single quotes around values.
Any ideas what i can do to make this small example work or is there any better way of doing this?
firstSqlStatement := true;
updateText := 'UPDATE T_EMPLOYEES SET ';
if FIRSTNAME IS NOT NULL and FIRSTNAME > 0 THEN
updateText:=updateText || ' firstName=''' || FIRSTNAME || ''' ';
firstSqlStatement := false;
end if;
if MIDDLENAME IS NOT NULL and length(MIDDLENAME) > 0 THEN
if firstSqlStatement = false THEN
updateText:=updateText || ',';
end if;
updateText:=updateText || ' middleName=''' || MIDDLENAME || ''' ';
firstSqlStatement := false;
end if;
updateText:=updateText || ' where upper(id)=upper(' || ID || ');';
DBMS_OUTPUT.put_line(updateText);
EXECUTE IMMEDIATE updateText;
use '''
Maybe you can do it this way.
declare
ll_employee_id number := 10;
lv_firstname varchar2(30) := 'Thomas';
lv_middlename varchar2(30) := null;
begin
update t_employees
set firstname = decode(lv_firstname, null, firstname, lv_firstname),
middlename = decode(lv_middlename, null, middlename, lv_middlename)
where employee_id = ll_employee_id;
end;
DECLARE
my_error exception;
sql_stmt VARCHAR2 (500);
v_char_field VARCHAR2 (500);
v_number_field NUMBER;
v_stmt_number NUMBER;
BEGIN
sql_stmt := 'UPDATE TABLE';
IF 1 = 1 -- REPLACE WITH CONDITION FOR SELECTION FIELD
THEN
sql_stmt := sql_stmt || 'field_1 = :1';
v_stmt_number := 1;
ELSIF 1 = 1 -- REPLACE WITH CONDITION FOR SELECTION FIELD
THEN
sql_stmt := sql_stmt || 'field_2 = :1';
v_stmt_number := 2;
ELSE
DBMS_OUTPUT.put_line ('Field unmanaged');
RAISE my_error;
END IF;
IF 1 = 1 -- REPLACE WITH CONDITION FOR SELECTION TYPE FIELD
THEN
EXECUTE IMMEDIATE sql_stmt USING v_char_field;
ELSIF 1 = 1 -- REPLACE WITH CONDITION FOR SELECTION TYPE FIELD
THEN
EXECUTE IMMEDIATE sql_stmt USING v_number_field;
ELSE
DBMS_OUTPUT.put_line ('Type Field unmanaged');
RAISE my_error;
END IF;
DBMS_OUTPUT.PUT_LINE ('STATEMENT NUMBER : ' || v_stmt_number);
DBMS_OUTPUT.PUT_LINE ('TOTAL RECORD UPDATE : ' || SQL%ROWCOUNT);
EXCEPTION
WHEN my_error
THEN
NULL;
WHEN OTHERS
THEN
DBMS_OUTPUT.PUT_LINE ('ERROR :' || SQLERRM);
END;
You can use multiple selections to compose your statement for selection fields to be updated and for the type.