An issue with Dynamic SQL within Package using REF CURSOR
Hi there,
In the following package first two procedures works file but since I have added the third one ( GET_CONTRACT_BY_DYN_SQL) it does not work for me. When I try to compile and save it gives below error.
"Error(6,15): PLS-00323: subprogram or cursor 'GET_CONTRACT_BY_DYN_SQL' is declared in a package specification and must be defined in the package body"
Can you please help?
Package Header
create or replace
PACKAGE CONTRACTS_PKG AS
TYPE T_CURSOR IS REF CURSOR;
PROCEDURE GET_CONRACTS (IO_CURSOR IN OUT T_CURSOR);
PROCEDURE GET_CONTRACT_BY_ID (I_CONTRACTID IN NUMBER, IO_CURSOR IN OUT T_CURSOR);
PROCEDURE GET_CONTRACT_BY_DYN_SQL(P_CONTRATID IN NUMBER, P_COLS IN VARCHAR2, IO_CURSOR IN OUT T_CURSOR);
END CONTRACTS_PKG;
Package Body
create or replace
PACKAGE BODY CONTRACTS_PKG AS
-- Get All Contracts
PROCEDURE GET_CONRACTS(IO_CURSOR IN OUT T_CURSOR)
IS
V_CURSOR T_CURSOR;
BEGIN
OPEN V_CURSOR FOR
SELECT * FROM CONTRACTS;
IO_CURSOR := V_CURSOR;
END GET_CONRACTS;
-- Get Contract By ID
PROCEDURE GET_CONTRACT_BY_ID(I_CONTRACTID IN NUMBER, IO_CURSOR IN OUT T_CURSOR)
IS
V_CURSOR T_CURSOR;
BEGIN
OPEN V_CURSOR FOR
SELECT * FROM CONTRACTS WHERE contract_id = I_CONTRACTID;
IO_CURSOR := V_CURSOR;
END GET_CONTRACT_BY_ID;
-- Get Contract Using Dynamic SQL
PROCEDURE GET_CONTRACT_BY_DYN_SQL(P_CONTRACTID IN NUMBER, P_COLS IN VARCHAR2, IO_CURSOR IN OUT T_CURSOR)
IS
V_CURSOR T_CURSOR;
V_SQL VARCHAR2(200);
BEGIN
V_SQL := 'SELECT '|| P_COLS || ' FROM CONTRACTS WHERE contract_id = ' || P_CONTRACTID ;
--OPEN V_CURSOR FOR
--EXECUTE IMMEDIATE V_SQL INTO V_CURSOR;
OPEN V_CURSOR FOR V_SQL;
EXECUTE IMMEDIATE V_SQL;
--IO_CURSOR := V_CURSOR;
END GET_CONTRACT_BY_DYN_SQL;
END CONTRACTS_PKG;
Thanks in advance.
Hitesh
Thanks guys. Finally I have tweaked as per your suggestions and it's working for all 3 cases (stored procedures).
Oracle
======
Package Header
create or replace
PACKAGE CONTRACTS_PKG AS
TYPE T_CURSOR IS REF CURSOR;
PROCEDURE GET_CONRACTS (IO_CURSOR IN OUT T_CURSOR);
PROCEDURE GET_CONTRACT_BY_ID (I_CONTRACTID IN NUMBER, IO_CURSOR IN OUT T_CURSOR);
PROCEDURE GET_CONTRACT_BY_DYN_SQL(P_CONTRACTID IN NUMBER, P_COLS IN VARCHAR2, IO_CURSOR IN OUT T_CURSOR);
END CONTRACTS_PKG;
Package Body
create or replace
PACKAGE BODY CONTRACTS_PKG AS
-- Get All Contracts
PROCEDURE GET_CONRACTS(IO_CURSOR IN OUT T_CURSOR)
IS
V_CURSOR T_CURSOR;
BEGIN
OPEN V_CURSOR FOR
SELECT * FROM CONTRACTS;
IO_CURSOR := V_CURSOR;
END GET_CONRACTS;
-- Get Contract By ID
PROCEDURE GET_CONTRACT_BY_ID(I_CONTRACTID IN NUMBER, IO_CURSOR IN OUT T_CURSOR)
IS
V_CURSOR T_CURSOR;
BEGIN
OPEN V_CURSOR FOR
SELECT * FROM CONTRACTS WHERE contract_id = I_CONTRACTID;
IO_CURSOR := V_CURSOR;
END GET_CONTRACT_BY_ID;
-- Get Contract Using Dynamic SQL
PROCEDURE GET_CONTRACT_BY_DYN_SQL(P_CONTRACTID IN NUMBER, P_COLS IN VARCHAR2, IO_CURSOR IN OUT T_CURSOR)
IS
V_CURSOR T_CURSOR;
V_SQL VARCHAR2(200);
BEGIN
IF p_contractid > 0 THEN
V_SQL := 'SELECT '|| P_COLS || ' FROM CONTRACTS WHERE contract_id = ' || P_CONTRACTID ;
ELSE
V_SQL := 'SELECT '|| P_COLS || ' FROM CONTRACTS';
END IF;
OPEN V_CURSOR FOR V_SQL;
IO_CURSOR := V_CURSOR;
END GET_CONTRACT_BY_DYN_SQL;
END CONTRACTS_PKG;
ColdFusion (calling app code)
=====================
<cfstoredproc procedure="CONTRACTS_PKG.GET_CONTRACT_BY_ID" datasource="#REQUEST.dsn#">
<cfprocparam cfsqltype="CF_SQL_INTEGER" type="in" value="1" variable="I_CONTRACTID">
<cfprocresult name="qData" resultset="1">
</cfstoredproc>
<br>Single Contract:
<cfdump var="#qData#" label="Single Contract">
<cfstoredproc procedure="CONTRACTS_PKG.GET_CONRACTS" datasource="#REQUEST.dsn#">
<cfprocresult name="qDataAll" resultset="1">
</cfstoredproc>
<br>All Contracts:
<cfdump var="#qDataAll#" label="All Contracts">
<cfstoredproc procedure="CONTRACTS_PKG.GET_CONTRACT_BY_DYN_SQL" datasource="#REQUEST.dsn#">
<cfprocparam cfsqltype="CF_SQL_INTEGER" type="in" value="1" variable="P_CONTRACTID">
<cfprocparam cfsqltype="CF_SQL_VARCHAR" type="in" value="contract_number,contract_title,created_date" variable="P_COLS">
<cfprocresult name="qDataDynSQL" resultset="1">
</cfstoredproc>
<br>Dynamic SQL Query:
<cfdump var="#qDataDynSQL#" label="Dynamic SQL Query">
Thanks,
Hitesh Patel
Similar Messages
-
I am using a dynamic SQL which generates a insert SQL at runtime.
DBMS_OUTPUT.PUT_LINE('CREATE_BACKUP');
L_DYNAMIC_SQL_SEL := ' ( SELECT ';
L_INDEX := 0 ;
FOR COLUMN IN TAB_COLUMNS(P_TABLE_NAME) LOOP
L_COLUMN_NAME := COLUMN.COLUMN_NAME ;
IF( L_INDEX > 0 ) THEN
L_COLUMN_NAME := ','||L_COLUMN_NAME;
END IF;
L_DYNAMIC_SQL_SEL := L_DYNAMIC_SQL_SEL || L_COLUMN_NAME;
L_INDEX := L_INDEX + 1 ;
END LOOP;
L_DYNAMIC_SQL_SEL := L_DYNAMIC_SQL_SEL || ' ,CAST(' ||P_CSM_ID ||' AS NUMBER(32)) AS CUST_SET_ID';
L_DYNAMIC_SQL_SEL := 'INSERT INTO '||P_BK_TABLE_NAME||L_DYNAMIC_SQL_SEL||' FROM '||P_TABLE_NAME ||' ) ;';
EXECUTE IMMEDIATE L_DYNAMIC_SQL_SEL;
The generated insert SQL looks like
INSERT INTO XX_YY_OPTIONS_B_BK ( SELECT MODULE_ID,APPLICATION_ID,PROFILE_OPTION_ID,PROFILE_OPTION_NAME,HIERARCHY_NAME,USER_ENABLED_FLAG,USER_UPDATEABLE_FLAG,SQL_VALIDATION,START_DATE_ACTIVE,END_DATE_ACTIVE,CREATION_DATE,CREATED_BY,LAST_UPDATE_DATE,LAST_UPDATED_BY,LAST_UPDATE_LOGIN,ENTERPRISE_ID ,CAST('1' AS NUMBER(32)) AS CUST_SET_ID FROM FND_PROFILE_OPTIONS_B ) ;
When calling EXECUTE IMMEDIATE L_DYNAMIC_SQL_SEL; it throws an exception "ORA-00911: invalid character" .At the same time If I execute the above query through SQL Plus, it inserts the data.
What could be the issue here? .Any pointers would be helpful.
ThanksRefer to http://docs.oracle.com/cd/B19306_01/appdev.102/b14261/executeimmediate_statement.htm
Especially the first paragragh under 'Usage notes'.
Sybrand Bakker
Senior Oracle DBA -
Alternative to native, dynamic sql to return a ref cursor to a client
I'm on Oracle 8.0.4, and would like to pass a string of values like '1,2,7,100,104' that are the primary key for a table. Then use something like:
procedure foo( MyCur RefCurType, vKey varchar2)
begin
open MyCur for
'select names from SomeTable' | |
' where ID in (' | | vKey | | ')'
end;
This would return a recordset to (in this case) a Crystal Reports report.
However, native dynamic SQL ain't available until 8.1.0. So can anyone think of a clever way to accomplish this, with a way to return a cursor? I can't figure out how to do this with DBMS_SQL, because open_cursor is just returning a handle, not a referene to a cursor that can be passed to a remote client.
Thanks in advance.I'm on Oracle 8.0.4, and would like to pass a string of values like '1,2,7,100,104' that are the primary key for a table. Then use something like:
procedure foo( MyCur RefCurType, vKey varchar2)
begin
open MyCur for
'select names from SomeTable' | |
' where ID in (' | | vKey | | ')'
end;
This would return a recordset to (in this case) a Crystal Reports report.
However, native dynamic SQL ain't available until 8.1.0. So can anyone think of a clever way to accomplish this, with a way to return a cursor? I can't figure out how to do this with DBMS_SQL, because open_cursor is just returning a handle, not a referene to a cursor that can be passed to a remote client.
Thanks in advance. -
I have a procedure which is using one ref cursor as OUT paramater. Now when I call this procedure, it gives me the following error:
ORA-00932: inconsistent datatypes: expected CURSER got NUMBER
ORA-06512: at "APPS.ORDER_RETURN1", line 8
ORA-06512: at "APPS.ORDER_RETURN2", line 4
ORA-06512: at line 1
Below is my code
PROCEDURE ORDER_RETURN1(p_order OUT sys_refcursor) IS
TYPE OE_ORDER_rcur IS REF CURSOR;
rcur OE_ORDER_rcur;
BEGIN
OPEN rcur FOR
SELECT ORDER_NUMBER FROM OE_ORDER_HEADERS_ALL WHERE ROWNUM < 4;
FETCH rcur INTO p_order;
CLOSE rcur;
END ORDER_RETURN1;
PROCEDURE ORDER_RETURN2 IS
OE_ORDER_rcur11 sys_refcursor;
BEGIN
ORDER_RETURN1(OE_ORDER_rcur11);
end;
I tried to call proc ORDER_RETURN1 with the help of proc ORDER_RETURN2, but no change, it gives me same error if i call the first proc ORDER_RETURN1 or i call ORDER_RETURN2.
I am stuck with this problem, I had used ref cursor in procedure but not able to call the procedure which uses ref cursor as OUT parameter.
Please help me to resolve this.
Thanks
Nidhi..Check out this
SQL>VARIABLE X REFCURSOR
SQL>CREATE OR REPLACE PROCEDURE ORDER_RETURN1(p_order OUT sys_refcursor) IS
2 BEGIN
3 OPEN p_order FOR
4 SELECT OBJECT_ID FROM ALL_OBJECTS WHERE ROWNUM < 4;
5 END ORDER_RETURN1;
6 /
Procedure created.
SQL>EXEC ORDER_RETURN1(:X)
PL/SQL procedure successfully completed.
SQL>PRINT X
OBJECT_ID
4
39
30
SQL>Regards
Arun -
Report using ref cursor or dynamic Sql
Hi,
I never create a report using a ref cursor or a dynamic sql. Could any one help me to solve the below issue.
I have 2 tables.
1. Student_Record
2. Student_csv_help
Student_Record the main table where the data is stored.
Student_csv_help will contain the all the column names of the Student_record.
CREATE TABLE Student_CSV_HELP
ENTRY_ID NUMBER,
RAW_NAME VARCHAR2(40 BYTE),
DESC_NAME VARCHAR2(1000 BYTE),
IN_OUTPUT_LIST VARCHAR2(1 BYTE)
SET DEFINE OFF;
Insert into TOA_CSV_HELP
(ENTRY_ID, RAW_NAME, DESC_NAME, IN_OUTPUT_LIST)
Values
(1, 'S_ID', 'Student ID', 'Y');
Insert into TOA_CSV_HELP
(ENTRY_ID, RAW_NAME, DESC_NAME, IN_OUTPUT_LIST)
Values
(2, 'S_Name', 'Student Name', 'Y');
Insert into TOA_CSV_HELP
(ENTRY_ID, RAW_NAME, DESC_NAME, IN_OUTPUT_LIST)
Values
(3, 'S_Join_date', 'Joining Date', 'Y');
Insert into TOA_CSV_HELP
(ENTRY_ID, RAW_NAME, DESC_NAME, IN_OUTPUT_LIST)
Values
(4, 'S_Address', 'Address', 'Y');
Insert into TOA_CSV_HELP
(ENTRY_ID, RAW_NAME, DESC_NAME, IN_OUTPUT_LIST)
Values
(5, 'S_Fee', 'Tution Fee', 'N');
commit;
CREATE TABLE Student_record
S_ID NUMBER,
S_Name VARCHAR2(100 BYTE),
S_Join_date date,
S_Address VARCHAR2(360 BYTE),
S_Fee Number
Insert into Student_record
(S_ID, S_Name, S_Join_date, S_Address,S_Fee)
Values
(101, 'john', TO_DATE('12/17/2009 08:00:00', 'MM/DD/YYYY HH24:MI:SS'), 'CA-94777', 2000);
Insert into Student_record
(S_ID, S_Name, S_Join_date, S_Address,S_Fee)
Values
(102, 'arif', TO_DATE('12/18/2009 08:00:00', 'MM/DD/YYYY HH24:MI:SS'), 'CA-94444', 3000);
Insert into Student_record
(S_ID, S_Name, S_Join_date, S_Address,S_Fee)
Values
(103, 'raj', TO_DATE('12/19/2009 08:00:00', 'MM/DD/YYYY HH24:MI:SS'), 'CA-94555', 2500);
Insert into Student_record
(S_ID, S_Name, S_Join_date, S_Address,S_Fee)
Values
(104, 'singh', TO_DATE('12/20/2009 08:00:00', 'MM/DD/YYYY HH24:MI:SS'), 'CA-94666', 2000);
Commit;
Now my requirement is:
I have a form with Student_record data block. When i Click on print Button on this form. It will open another window which has Student_CSV_HELP.DESC_NAME and a check box before this.
The window look like as below:
check_box DESC_NAME+
X S_ID+
-- S_Name+
X S_Join_date+
X S_Address+
-- S_Fee+
X means check box checked.+
-- means check box Unchecked.+
After i selected these check boxes i will send 2 parameters to the report server
1. a string parameter to the report server which has the value 'S_ID,S_Join_date,S_Address' (p_column_name := 'S_ID,S_Join_date,S_Address');
2. the s_id value from the student_record block (p_S_id := '101');
Now my requirement is when i click on run. I need a report like as below:
Student ID : 101+
Joining Date : 12/17/2009 08:00:00+
Address : CA-94777+
This is nothing but the ref cursor should run like as below:
Select S_id from student_record block S_id = :p_S_id;
Select S_Join_date from student_record block S_id = :p_S_id;
Select S_Address from student_record block S_id = :p_S_id;
So, according to my understanding i have to select the columns at the run time. I dont have much knowledge in creating reports using ref cursor or dynamic sql.
So please help me to solve this issue.
Thanks in advance.Plain sql should satisfy your need. Try ....
Select S_id, S_Join_date, S_Address
from student_record
where S_id = :p_S_id -
Hello,
I have the following function that works ok:
CREATE OR REPLACE FUNCTION Get_Partition_Name (sTable VARCHAR2, iImportIndex INTEGER)
RETURN VARCHAR2 IS
cursor c is select A.partition_name from (select table_name, partition_name,
extractvalue (
dbms_xmlgen.
getxmltype (
'select high_value from all_tab_partitions where table_name='''
|| table_name
|| ''' and table_owner = '''
|| table_owner
|| ''' and partition_name = '''
|| partition_name
|| ''''),
'//text()') import_value from all_tab_partitions) A where table_name = sTable and A.import_value = iImportIndex;
sPartitionName VARCHAR(20);
err_num NUMBER;
BEGIN
open c;
fetch c into sPartitionName;
IF c%ISOPEN THEN
CLOSE c;
END IF;
RETURN sPartitionName;
EXCEPTION
WHEN OTHERS THEN
err_num := SQLCODE;
--save error in log table
LOG.SAVELINE(SQLCODE, SQLERRM);
END Get_Partition_Name;
I am trying to replace the cursor statement with dynamic SQL, something like (see below) but it doesn't work any more; I think I am missing some quotes.
CREATE OR REPLACE FUNCTION Get_Partition_Name (sTable VARCHAR2, iImportIndex INTEGER)
RETURN VARCHAR2 IS
TYPE t1 IS REF CURSOR;
c t1;
sSql VARCHAR2(500);
sPartitionName VARCHAR(20);
err_num NUMBER;
BEGIN
sSql := 'select A.partition_name from (select table_name, partition_name,
extractvalue (
dbms_xmlgen.
getxmltype (
''select high_value from all_tab_partitions where table_name=''''
|| table_name
|| '''' and table_owner = ''''
|| table_owner
|| '''' and partition_name = ''''
|| partition_name
|| ''''''),
''//text()'') import_value from all_tab_partitions) A where table_name = :a and A.import_value = :b';
OPEN c FOR sSql USING sTable, iImportIndex;
fetch c into sPartitionName;
IF c%ISOPEN THEN
CLOSE c;
END IF;
RETURN sPartitionName;
EXCEPTION
WHEN OTHERS THEN
err_num := SQLCODE;
--save error in log table
LOG.SAVELINE(SQLCODE, SQLERRM);
END Get_Partition_Name;
Please advise,
Regards,
M.R.Assuming the requirement is to find the partition in the supplied table with the supplied high value and the issue is that dba/all_tab_partitions.high_value is a long, one alternative along the same lines as you've done already is as follows. (I've just used a cursor rather than a function for simplicity of demo).
SQL> var r refcursor
SQL> set autoprint on
SQL> declare
2 ctx dbms_xmlgen.ctxhandle;
3 v_table_name VARCHAR2(40) := 'LOGMNR_USER$';
4 v_value NUMBER := 100;
5 begin
6 ctx := DBMS_XMLGEN.NEWCONTEXT
7 ('select table_name
8 , partition_name
9 , high_value hi_val
10 from dba_tab_partitions
11 where table_name = :table_name');
12 dbms_xmlgen.setbindvalue(ctx,'TABLE_NAME',v_table_name);
13 open:r for
14 with x as
15 (select xmltype(dbms_xmlgen.getxml(ctx)) myxml
16 from dual)
17 select extractvalue(x.object_value,'/ROW/TABLE_NAME') table_name
18 , extractvalue(x.object_value,'/ROW/PARTITION_NAME') partition_name
19 , extractvalue(x.object_value,'/ROW/HI_VAL') hi_val
20 from x
21 , TABLE(XMLSEQUENCE(EXTRACT(x.myxml,'/ROWSET/ROW'))) x
22 where extractvalue(x.object_value,'/ROW/HI_VAL') = v_value;
23 end;
24 /
PL/SQL procedure successfully completed.
TABLE_NAME
PARTITION_NAME
HI_VAL
LOGMNR_USER$
P_LESSTHAN100
100
SQL> I'm sure there are other ways as well. Especially with XML functionality, there's normally many ways to skin a cat. -
Problem with XSU when trying to execute pl/sql package returning ref cursor
Hi,
I'm exploring xsu with 8i database.
I tried running sample program which I took from oracle
documentation. Here is the details of these.
------create package returning ref cursor---
CREATE OR REPLACE package testRef is
Type empRef IS REF CURSOR;
function testRefCur return empRef;
End;
CREATE OR REPLACE package body testRef is
function testRefCur RETURN empREF is
a empREF;
begin
OPEN a FOR select * from emp;
return a;
end;
end;
---------package successfully created-----
Now I use java program to generate xml data from ref cursor
------------java program ----------
import org.w3c.dom.*;
import oracle.xml.parser.v2.*;
import java.sql.*;
import oracle.jdbc.driver.*;
import oracle.xml.sql.query.OracleXMLQuery;
import java.io.*;
public class REFCURt
public static void main(String[] argv)
throws SQLException
String str = null;
Connection conn = getConnection("scott","tiger"); //
create connection
// Create a ResultSet object by calling the PL/SQL function
CallableStatement stmt =
conn.prepareCall("begin ? := testRef.testRefCur();
end;");
stmt.registerOutParameter(1,OracleTypes.CURSOR); // set
the define type
stmt.execute(); // Execute the statement.
ResultSet rset = (ResultSet)stmt.getObject(1); // Get the
ResultSet
OracleXMLQuery qry = new OracleXMLQuery(conn,rset); //
prepare Query class
try
qry.setRaiseNoRowsException(true);
qry.setRaiseException(true);
qry.keepCursorState(true); // set options (keep the
cursor alive..
System.out.println("..before printing...");
while ((str = qry.getXMLString())!= null)
System.out.println(str);
catch(oracle.xml.sql.OracleXMLSQLNoRowsException ex)
System.out.println(" END OF OUTPUT ");
qry.close(); // close the query..!
// qry.close(); // close the query..!
// Note since we supplied the statement and resultset,
closing the
// OracleXMLquery instance will not close these. We would
need to
// explicitly close this ourselves..!
stmt.close();
conn.close();
// Get the connection given the user name and password..!
private static Connection getConnection(String user, String
passwd)
throws SQLException
DriverManager.registerDriver(new
oracle.jdbc.driver.OracleDriver());
Connection conn = DriverManager.getConnection
("jdbc:oracle:thin:@xxxx:1521:yyyy",user,passwd);
return conn;
when I ran the program after successful compilation,I got the
following error
==========
Exception in thread "main" oracle.xml.sql.OracleXMLSQLException:
1
at oracle.xml.sql.core.OracleXMLConvert.getXML(Compiled
Code)
at oracle.xml.sql.query.OracleXMLQuery.getXMLString
(OracleXMLQuery.java:263)
at oracle.xml.sql.query.OracleXMLQuery.getXMLString
(OracleXMLQuery.java:217)
at oracle.xml.sql.query.OracleXMLQuery.getXMLString
(OracleXMLQuery.java:194)
at REFCURt.main(Compiled Code)
============================
Can anybody tell me why I'm getting this error.Am I missing any
settings?
thanksWe are using 8.1.7 Oracle db with latest xdk loaded.
am I missing any settings? -
Backup DB with dynamic sql - want to substitute in dbname and disk file path
Re: Backup DB with dynamic sql - want to substitute in dbname and disk file path
Hope I can explain this. Below is a small snippet of code. I want to set @SQLTemplate_TSQL once at the top of the script and then execute the SET @SQLCommand and sp_executesql in a loop that reads a list of databases. It all works, except for the
BACKUP DATABASE. Right now it evaluates when the SET @SQLTemplate_TSQL is evaluated. I want it to evaluate when it is executed. I want the DB_NAME() of the USE @dbname.
-- change @dbname and @dbbackuppath
DECLARE @SQLCommand NVARCHAR(MAX)
DECLARE @SQLTemplate_TSQL NVARCHAR(MAX)
DECLARE @dbname varchar(128) = 'Bank04'
-- one time setting of @SQLTemplate_TSQL
set @SQLTemplate_TSQL =
DECLARE @dbbackuppath varchar(128) = ''''d:\backups''''
IF RIGHT(@dbbackuppath, 1) <> ''''\''''
SET @dbbackuppath = @dbbackuppath + ''''\''''
SET @dbbackuppath = @dbbackuppath + DB_Name() + ''''.bak''''
PRINT @dbbackuppath
BACKUP DATABASE ' + DB_NAME() + ' to DISK=''' + QUOTENAME(@dbbackuppath, CHAR(39)) + '''
-- Execute this several times over different databases
SET @SQLCommand = '
USE ' + QUOTENAME(@dbname) + ';
EXEC(''' + @SQLTemplate_TSQL + ''') '
PRINT @SQLCommand
EXECUTE sp_executesql @SQLCommandHere is a stripped down version of my code. Someone writes a script. I then take the script and seperate it by GO statement block. Each GO block gets its own row into the
#SQLTemplate_TSQL. I then replace single quote with 4 quotes and run it. Then I run against my list of databases. I am unable to get the BACKUP DATA base to work with this model.
Run scripts against multiple databases.sql
Do a FIND on "CHANGE THIS" to see the databases returned from the SELECT statement
DECLARE @DatabaseName varchar(128)
DECLARE @SQLCommand NVARCHAR(MAX)
DECLARE @SQLTemplate_Seq INT
DECLARE @SQLTemplate_OperationDesc NVARCHAR(128)
DECLARE @SQLTemplate_TSQL NVARCHAR(MAX)
DECLARE @SQLTemplate_Diagnostics INT
DECLARE @Note VARCHAR(500)
IF OBJECT_ID('tempdb..#SQLTemplate_TSQL') IS NOT NULL
DROP TABLE #SQLTemplate_TSQL
CREATE TABLE [dbo].[#SQLTemplate_TSQL](
[SQLTemplate_RecID] [int] Identity,
[SQLTemplate_ID] [int] NOT NULL,
[SQLTemplate_Seq] [int] NOT NULL,
[SQLTemplate_OperationDesc] [varchar](128) NOT NULL,
[SQLTemplate_TSQL] [varchar](max) NOT NULL,
[SQLTemplate_Diagnostics] [int] NOT NULL,
[SQLTemplate_Enabled] [int] NOT NULL)
DELETE FROM #SQLTemplate_TSQL WHERE SQLTemplate_Seq = 65
DECLARE @SeqID INT
SELECT @SeqID = MAX(SQLTemplate_ID) FROM #SQLTemplate_TSQL
SET @SeqID = ISNULL(@SeqID,0)
SET @SeqID = @SeqID + 1
INSERT INTO #SQLTemplate_TSQL VALUES(@SeqID ,65,@SeqID,'
SELECT * FROM ifs_config
',1,1)
SET @SeqID = @SeqID + 1
INSERT INTO #SQLTemplate_TSQL VALUES(@SeqID ,65,@SeqID,'
DECLARE @HistoryODS INT
SET @HistoryODS = 1
SELECT * FROM ifs_tablelist WHERE HistoryODS = @HistoryODS and Tablename like ''''%HIST%''''
',1,1)
-- Setup Cursor to Loop through each of the Prior Period databases
DECLARE db_cursor CURSOR FOR
SELECT [Database Name] --<<<<<<<< CHANGE THIS SELECT statement to select DBs >>>>>>
FROM v_ifs_PPODSDBInfo_Curr
WHERE [Database Frequency] <> 'CURRENT'
ORDER BY [Database Frequency], [Database Number]
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @DatabaseName
-- Loop through each of the databases
WHILE @@FETCH_STATUS = 0
BEGIN
-- Setup Cursor to Loop through each of the SQL Statements
DECLARE #SQLTemplate_TSQL_cursor CURSOR FOR
SELECT [SQLTemplate_TSQL], [SQLTemplate_OperationDesc], [SQLTemplate_Seq], [SQLTemplate_Diagnostics]
FROM #SQLTemplate_TSQL
WHERE [SQLTemplate_Enabled] = 1 AND SQLTemplate_Seq = 65
ORDER BY SQLTemplate_ID
OPEN #SQLTemplate_TSQL_cursor
FETCH NEXT FROM #SQLTemplate_TSQL_cursor INTO @SQLTemplate_TSQL, @SQLTemplate_OperationDesc, @SQLTemplate_Seq, @SQLTemplate_Diagnostics
-- Loop through each of the SQL statements
WHILE @@FETCH_STATUS = 0
BEGIN
SET @SQLCommand = '
USE ' + QUOTENAME(@Databasename) + ';
EXEC(''' + @SQLTemplate_TSQL + ''') '
EXECUTE sp_executesql @SQLCommand
FETCH NEXT FROM #SQLTemplate_TSQL_cursor INTO @SQLTemplate_TSQL, @SQLTemplate_OperationDesc, @SQLTemplate_Seq, @SQLTemplate_Diagnostics
END
CLOSE #SQLTemplate_TSQL_cursor
DEALLOCATE #SQLTemplate_TSQL_cursor
FETCH NEXT FROM db_cursor INTO @DatabaseName
END
CLOSE db_cursor
DEALLOCATE db_cursor -
Writing to a temp table in a stored procedure with dynamic sql
Hi
I am writing into a temp table with dynamic sql:
select coloum_name into #temp_table from
+
@DestinationDBName+'.information_schema.tables
and then I am trying to use #temp_table in the procedure:
select coloum_name into #anotherTable from #temp_table
but I am getting an error that #temp_table is not recognized.
Can a temp table not be used in dynamic sql ?
How can I overcome this problem ?Temp Table Can used easily in Dynamic Query in SQL Server and here is small Exmaple you can check it and do like it
CREATE PROC test
AS
BEGIN
CREATE TABLE #T1
(ID int , NAME Nvarchar(50))
CREATE TABLE #T2
(ID int , NAME Nvarchar(50))
DECLARE @SQL NVARCHAR(MAX)='Insert into #T1
SELECT database_id , Name FROM Sys.Databases
Insert into #T2 Select ID , Name from #T1 '
EXEC SP_ExecuteSQL @SQL
SELECT * FROM #T2
DROP TABLE #T1
DROP TABLE #T2
END
Exec Test
If you found My reply is helpful for you please vote me
thanks
Mustafa EL-Masry
Principle Database Administrator & DB Analyst
SQL Server MCTS-MCITP
M| +966 54 399 0968
MostafaElmasry.Wordpress.Com -
Does anyone out there use dynamic SQL with DB2? If so, are the sql statements causing a PreparedStatement to be executed on DB2. I posted this question similarly before, but never resolved it, and it is killing me. I have to resolve this ASAP!
Here is the problem: My DB2 Admin says that EVERY TIME I access the database, my Java app is causing the database to create a PreparedStatement. However, I'm using Statement objects exclusively, with dynamic SQL. He says that DB2 needs an "access path" for the client, and that it converts the Statement to a PreparedStatement, as this is the only way to get this "access path". He says the only solution is either stored procedures or SQLJ, which will do the binding in advance, and increase performance tremendously. However, I am STRONGLY opposed to using SQLJ, and if we do stored procedures, we'd have to write one for every possible SQL statment! I KNOW there is a better solution.
Is anyone out there having these problems with JDBC and DB2? Surely someone out there uses DB2 and JDBC and either has these problems or can confirm that something is incorrectly configured on the database side.
Any help would be great. Thanks, WillNow I'm wondering if maybe the PreparedStatements are ONLY being called on the database when I call getConnection(), and not when I call executeQuery() or executeUpdate() from the Statement object. I just can't see why the database would have to make an access path for every SQL statement executed, but I could see it creating an access path for every connection requested. Any thoughts on that theory?
-
My MacBook Pro 13" (2012) is running Windows 7 on Bootcamp and there is an issue with the headset I'm using. I use a cheap Logitech Stereo Headset H130, but since there is only on audio plugin on the computer, I purchased a 3.5 mm 4-pin smartphone audio adapter thingy. That allowed me to put both my the sound coming to my headset & the microphone on my headset onto one wire. Everything worked wonderfully when running the Mac OS since they probably have support for that kind of stuff. The problem is though that once I try to use the same method in Windows 7, the OS doesn't recognize my headset microphone at all, but, instead when recording my voice decides to use the built-in mac microphone. Using this adapter still allows me to hear from my headset, but not use the microphone and that becomes a problem. It might be so that Windows 7 doesn't have support\drivers for that... How should I continue from here on out? Any advice?
From what I have read from others on here you may be out of luck. You would need the appropriate Windows drivers for the Cirrus chip in the Mac and no one has been able to successfully locate them. Apple wouldn't support this since Windows is an optional install.
Sorry to bring the bad news. -
Issue with PR conversion to PO using ME59 withqty of similar line items
Hi All,
I'm having an issue with PR conversion to PO using ME59
I have a PR with the following line items with all same details except quantity
ex 1
Mat Qty Unit Plant St Loc
M1 1 EA P1 S1
M1 29 EA P1 S1
The PR brings in the Unit automatically
EA is Base Unit Of Measure -Material Master
BT is Order Unit -Material Master
Conversion
30 EA = 1BT
When i convert this PR to PO using ME59N then i see 2 lines items
M1 1 BT
M2 1 BT
Its doubling the qty (2 BT = 60 EA)
ex 2
Mat Qty Unit Plant St Loc
M1 1 EA P1 S1
M1 2 EA P1 S1
M1 27 EA P1 S1
The PR brings in the Unit automatically
EA is Base Unit Of Measure -Material Master
BT is Order Unit -Material Master
Conversion
30 EA = 1BT
When i convert this PR to PO using ME59N then i see 2 lines items
M1 1 BT
M1 1 BT
M1 1 BT
Its 3 times no
PR Qty = 30 EA
PO qty = 3 BT = 90 EA
I guess during conversion to PO
It sees PR Line item 1 and looks for another line items with similar fields ( in our case it sees line 2 in ex 1 and 2 and 3 in ex 2)
i adds the qty 1 and 29 in ex1 and converts the total 30 each to 1 BT and when it moves to 2 line it see item1 and again creates 1BT but the line item 2 was already considered and it should be ignored
Similarly if you see ex2 then it creates 3 limes with 1 BT each
Let me know how to resolve this issue
ThanksAs for std SAP ME59N - make sure there is not rounding value is activated in the Material master as well as info record
If this is not the case than check any custom code is activated for ME59N
becuase generally in many compnay when they use ME59n they don't want the same material from diff PR to create the diff line item in the PO so using the custom logic in the user exist they trick the code
it might be the case for you where you have issue. -
Hi All,
I am getting issue with pl/sql client saying readonly access to DMPROD(database).
could you help me out..what might be causing this problem or how to overcome it?
Thanks a lot.tvenkatesh07 wrote:
Hi All,
I am getting issue with pl/sql client saying readonly access to DMPROD(database).
could you help me out..what might be causing this problem or how to overcome it?Well, it could be possible that your user, with whom you are trying to connect, is having only read-only access to the db? Did you try to change the user?
Aman.... -
Dynamic SQL within a SQL Query ?
is there any possibility to do like this ?
SELECT table_name, XXXXXXXX('SELECT Count(*) FROM '||table_name) tot_rows
FROM dba_tables
WHERE owner = 'SCOTT';or any other trick to run dynamic SQL within the SQL Query?
Hoping....that it should be.
Regards,
OrapdevOne small disadvantage: it is executing 202 SQL statements: 3 "user SQL statements" (the one above and the 2 "select count(*)..."), and 199 internal ones ...How did you get to those numbers?
I just traced this statement and found completely different results:
TKPROF: Release 10.2.0.3.0 - Production on Tue Jul 10 12:12:10 2007
Copyright (c) 1982, 2005, Oracle. All rights reserved.
Trace file: diesl10r2_ora_5440.trc
Sort options: default
count = number of times OCI procedure was executed
cpu = cpu time in seconds executing
elapsed = elapsed time in seconds executing
disk = number of physical reads of buffers from disk
query = number of buffers gotten for consistent read
current = number of buffers gotten in current mode (usually for update)
rows = number of rows processed by the fetch or execute call
declare cursor NlsParamsCursor is SELECT * FROM
nls_session_parameters;begin SELECT Nvl(Lengthb(Chr(65536)),
Nvl(Lengthb(Chr(256)), 1)) INTO :CharLength FROM dual; for NlsRecord in
NlsParamsCursor loop if NlsRecord.parameter = 'NLS_DATE_LANGUAGE' then
:NlsDateLanguage := NlsRecord.value; elsif NlsRecord.parameter =
'NLS_DATE_FORMAT' then :NlsDateFormat := NlsRecord.value; elsif
NlsRecord.parameter = 'NLS_NUMERIC_CHARACTERS' then
:NlsNumericCharacters := NlsRecord.value; elsif NlsRecord.parameter =
'NLS_TIMESTAMP_FORMAT' then :NlsTimeStampFormat := NlsRecord.value;
elsif NlsRecord.parameter = 'NLS_TIMESTAMP_TZ_FORMAT' then
:NlsTimeStampTZFormat := NlsRecord.value; end if; end loop;end;
call count cpu elapsed disk query current rows
Parse 1 0.00 0.00 0 0 0 0
Execute 1 0.00 0.00 0 0 0 1
Fetch 0 0.00 0.00 0 0 0 0
total 2 0.00 0.00 0 0 0 1
Misses in library cache during parse: 0
Optimizer mode: ALL_ROWS
Parsing user id: 50
SELECT NVL(LENGTHB(CHR(65536)), NVL(LENGTHB(CHR(256)), 1))
FROM
DUAL
call count cpu elapsed disk query current rows
Parse 1 0.00 0.00 0 0 0 0
Execute 1 0.01 0.00 0 0 0 0
Fetch 1 0.00 0.00 0 0 0 1
total 3 0.01 0.00 0 0 0 1
Misses in library cache during parse: 0
Optimizer mode: ALL_ROWS
Parsing user id: 50 (recursive depth: 1)
Rows Row Source Operation
1 FAST DUAL (cr=0 pr=0 pw=0 time=7 us)
SELECT *
FROM
NLS_SESSION_PARAMETERS
call count cpu elapsed disk query current rows
Parse 1 0.00 0.00 0 0 0 0
Execute 1 0.00 0.00 0 0 0 0
Fetch 1 0.00 0.00 0 0 0 17
total 3 0.00 0.00 0 0 0 17
Misses in library cache during parse: 0
Optimizer mode: ALL_ROWS
Parsing user id: 50 (recursive depth: 1)
Rows Row Source Operation
17 FIXED TABLE FULL X$NLS_PARAMETERS (cr=0 pr=0 pw=0 time=124 us)
select PARAMETER,VALUE
from
nls_session_parameters where PARAMETER in('NLS_NUMERIC_CHARACTERS',
'NLS_DATE_FORMAT','NLS_CURRENCY')
call count cpu elapsed disk query current rows
Parse 1 0.00 0.00 0 0 0 0
Execute 1 0.00 0.00 0 0 0 0
Fetch 1 0.00 0.00 0 0 0 3
total 3 0.00 0.00 0 0 0 3
Misses in library cache during parse: 0
Optimizer mode: ALL_ROWS
Parsing user id: 50
Rows Row Source Operation
3 FIXED TABLE FULL X$NLS_PARAMETERS (cr=0 pr=0 pw=0 time=57 us)
select to_char(9,'9C')
from
dual
call count cpu elapsed disk query current rows
Parse 1 0.00 0.00 0 0 0 0
Execute 1 0.00 0.00 0 0 0 0
Fetch 1 0.00 0.00 0 0 0 1
total 3 0.00 0.00 0 0 0 1
Misses in library cache during parse: 0
Optimizer mode: ALL_ROWS
Parsing user id: 50
Rows Row Source Operation
1 FAST DUAL (cr=0 pr=0 pw=0 time=2 us)
SELECT table_name,
DBMS_XMLGEN.getxmltype ('select count(*) c from ' || table_name).EXTRACT
('//text').getstringval
() tot
FROM dba_tables
WHERE table_name IN ('EMP', 'DEPT') AND owner = 'SCOTT'
call count cpu elapsed disk query current rows
Parse 1 0.00 0.00 0 0 0 0
Execute 1 0.00 0.00 0 0 0 0
Fetch 1 0.01 0.02 0 48 0 2
total 3 0.01 0.02 0 48 0 2
Misses in library cache during parse: 0
Optimizer mode: ALL_ROWS
Parsing user id: 50
Rows Row Source Operation
2 HASH JOIN (cr=42 pr=0 pw=0 time=2952 us)
2 MERGE JOIN CARTESIAN (cr=42 pr=0 pw=0 time=1206 us)
2 NESTED LOOPS OUTER (cr=42 pr=0 pw=0 time=478 us)
2 NESTED LOOPS OUTER (cr=36 pr=0 pw=0 time=421 us)
2 NESTED LOOPS OUTER (cr=30 pr=0 pw=0 time=379 us)
2 NESTED LOOPS OUTER (cr=30 pr=0 pw=0 time=365 us)
2 NESTED LOOPS (cr=22 pr=0 pw=0 time=312 us)
2 NESTED LOOPS (cr=16 pr=0 pw=0 time=272 us)
2 NESTED LOOPS (cr=8 pr=0 pw=0 time=172 us)
1 TABLE ACCESS BY INDEX ROWID USER$ (cr=2 pr=0 pw=0 time=56 us)
1 INDEX UNIQUE SCAN I_USER1 (cr=1 pr=0 pw=0 time=30 us)(object id 44)
2 INLIST ITERATOR (cr=6 pr=0 pw=0 time=111 us)
2 TABLE ACCESS BY INDEX ROWID OBJ$ (cr=6 pr=0 pw=0 time=87 us)
2 INDEX RANGE SCAN I_OBJ2 (cr=4 pr=0 pw=0 time=54 us)(object id 37)
2 TABLE ACCESS CLUSTER TAB$ (cr=8 pr=0 pw=0 time=98 us)
2 INDEX UNIQUE SCAN I_OBJ# (cr=4 pr=0 pw=0 time=26 us)(object id 3)
2 TABLE ACCESS CLUSTER TS$ (cr=6 pr=0 pw=0 time=39 us)
2 INDEX UNIQUE SCAN I_TS# (cr=2 pr=0 pw=0 time=13 us)(object id 7)
2 TABLE ACCESS CLUSTER SEG$ (cr=8 pr=0 pw=0 time=37 us)
2 INDEX UNIQUE SCAN I_FILE#_BLOCK# (cr=4 pr=0 pw=0 time=21 us)(object id 9)
0 INDEX UNIQUE SCAN I_OBJ1 (cr=0 pr=0 pw=0 time=4 us)(object id 36)
2 TABLE ACCESS BY INDEX ROWID OBJ$ (cr=6 pr=0 pw=0 time=33 us)
2 INDEX UNIQUE SCAN I_OBJ1 (cr=4 pr=0 pw=0 time=23 us)(object id 36)
2 TABLE ACCESS CLUSTER USER$ (cr=6 pr=0 pw=0 time=28 us)
2 INDEX UNIQUE SCAN I_USER# (cr=2 pr=0 pw=0 time=12 us)(object id 11)
2 BUFFER SORT (cr=0 pr=0 pw=0 time=716 us)
1 FIXED TABLE FULL X$KSPPI (cr=0 pr=0 pw=0 time=661 us)
1436 FIXED TABLE FULL X$KSPPCV (cr=0 pr=0 pw=0 time=1449 us)
select count(*) c
from
EMP
call count cpu elapsed disk query current rows
Parse 1 0.00 0.00 0 0 0 0
Execute 1 0.00 0.00 0 0 0 0
Fetch 2 0.00 0.00 0 1 0 1
total 4 0.00 0.00 0 1 0 1
Misses in library cache during parse: 0
Optimizer mode: ALL_ROWS
Parsing user id: 50 (recursive depth: 1)
Rows Row Source Operation
1 SORT AGGREGATE (cr=1 pr=0 pw=0 time=96 us)
14 INDEX FULL SCAN EMP_IDX (cr=1 pr=0 pw=0 time=46 us)(object id 61191)
select metadata
from
kopm$ where name='DB_FDO'
call count cpu elapsed disk query current rows
Parse 1 0.00 0.00 0 0 0 0
Execute 1 0.00 0.00 0 0 0 0
Fetch 1 0.00 0.00 0 2 0 1
total 3 0.00 0.00 0 2 0 1
Misses in library cache during parse: 0
Optimizer mode: CHOOSE
Parsing user id: SYS (recursive depth: 1)
Rows Row Source Operation
1 TABLE ACCESS BY INDEX ROWID KOPM$ (cr=2 pr=0 pw=0 time=42 us)
1 INDEX UNIQUE SCAN I_KOPM1 (cr=1 pr=0 pw=0 time=22 us)(object id 365)
select count(*) c
from
DEPT
call count cpu elapsed disk query current rows
Parse 1 0.00 0.00 0 0 0 0
Execute 1 0.00 0.00 0 0 0 0
Fetch 2 0.00 0.00 0 1 0 1
total 4 0.00 0.00 0 1 0 1
Misses in library cache during parse: 0
Optimizer mode: ALL_ROWS
Parsing user id: 50 (recursive depth: 1)
ALTER SESSION SET sql_trace=FALSE
call count cpu elapsed disk query current rows
Parse 1 0.00 0.00 0 0 0 0
Execute 1 0.00 0.00 0 0 0 0
Fetch 0 0.00 0.00 0 0 0 0
total 2 0.00 0.00 0 0 0 0
Misses in library cache during parse: 0
Parsing user id: 50
OVERALL TOTALS FOR ALL NON-RECURSIVE STATEMENTS
call count cpu elapsed disk query current rows
Parse 5 0.00 0.00 0 0 0 0
Execute 5 0.00 0.00 0 0 0 1
Fetch 3 0.01 0.02 0 48 0 6
total 13 0.01 0.03 0 48 0 7
Misses in library cache during parse: 0
OVERALL TOTALS FOR ALL RECURSIVE STATEMENTS
call count cpu elapsed disk query current rows
Parse 5 0.00 0.00 0 0 0 0
Execute 5 0.01 0.00 0 0 0 0
Fetch 7 0.00 0.00 0 4 0 21
total 17 0.01 0.00 0 4 0 21
Misses in library cache during parse: 0
9 user SQL statements in session.
1 internal SQL statements in session.
10 SQL statements in session.
Trace file: diesl10r2_ora_5440.trc
Trace file compatibility: 10.01.00
Sort options: default
1 session in tracefile.
9 user SQL statements in trace file.
1 internal SQL statements in trace file.
10 SQL statements in trace file.
10 unique SQL statements in trace file.
132 lines in trace file.
0 elapsed seconds in trace file.I only see a ratio of 1:9 for user- to internal SQL statements?
michaels> select * from v$version
BANNER
Oracle Database 10g Enterprise Edition Release 10.2.0.3.0 - Prod
PL/SQL Release 10.2.0.3.0 - Production
CORE 10.2.0.3.0 Production
TNS for 32-bit Windows: Version 10.2.0.3.0 - Production
NLSRTL Version 10.2.0.3.0 - Production -
Issue with Dynamic Link with Premiere CC and After Effects
I'm having a strange and annoying issue with Dynamic linked clips in Premiere CC:
When I render or export my timeline the progress will stall when it hits a dynamic linked clip. It will stay stalled until I click the After Effects application and make it the active window. Once that happens the render/export resumes at normal speed.
This is annoying as I can't start a render and walk away or work on different windows, I have to babysit all the renders to make sure they go through.
Has anybody experienced this and know of any solutions?
I'm running the latest version of Premiere (7.2.1) and After Effects 12.2.0.52 on Mavericks 10.9.1 with a GTX 770 Video Card.Does it still pause if AE is closed completely? I often experience slower AME renders from Premiere over dynamic link material when AE is open. Closing AE speeds things up. Go figure.
Maybe you are looking for
-
I want to use my second external hard drive as a "flash drive"
Forgive my ignorance, but I would appreciate any input before I purchase and set up a second external hard drive.... I have a MyBook that I use with Time Machine and it has been great. However, it's approaching more full than I want it to get and I n
-
Do i need to use the skype APP, to call the skype-...
my international calling costs too much with my provider but with skype to go it says skype charges you.. but do you need to call via the app?
-
hi , can any one tell me the procedure to create tab strip wizard? urgent. with warm regards, khadar.
-
Running Non-Mac Programs (7.1 Headset)?
Hi, So I bought a headset and it works fine with my Mac but I need to get Logitech's software for the Headset to be true 7.1 surround sound (http://www.logitech.com/en-nz/support/g430-7-1-surround-sound-gaming-headset?cri d=411) under "Downloads" how
-
Will a Performance upgrade occur after clean install?
I currently have a three yr old MBP that had Leopard on it and was upgraded to Snow Leopard. I also upgraded the hard drive. Over the years, I have lots of programs and files and have a complete TM backup. I am thinking its time for some system cl