Migrating SQL Script to stored procedure...
I created a SQL script file to run in SQLPlus to
generate a fixed-format text file (See EDI_PrepForSend
below)
How do i do the same thing in a stored
package/procedure? Can I utilize the
script I already have working? I need to
do it in a stored procedure because I need
to do dynamic queries.
TIA
Chuck Plinta
[email protected]
++++++++++++++++++++++++++
-- EDI_PrepForSend.sql
SET CONCAT '#';
SET ESCAPE OFF;
SET TERM OFF
-- Set's for flat file
SET NEWPAGE 0
SET SPACE 0
SET LINESIZE 50
SET PAGESIZE 0
SET ECHO OFF
SET FEEDBACK OFF
SET HEADING OFF
SET VERIFY OFF
SPOOL o:\ClientData\EDI-Send\&2\EDI-HCFA-Dtl-&1-&3.txt
COLUMN MC_Number FORMAT A15 HEADING MC_Number
COLUMN MC_Line_Number FORMAT A3 HEADING Ln#
COLUMN MC_CPT_Code FORMAT A5 HEADING Code
COLUMN MC_CPT_Modifier FORMAT A2 HEADING Mod
COLUMN MC_FDOS FORMAT A8 HEADING FDOS
COLUMN MC_LDOS FORMAT A8 HEADING LDOS
COLUMN MC_Line_Charge FORMAT 99999.99 HEADING Charge
SELECT MC.ICN MC_Number,
'???' MC_Line_Number,
MC.CPT_Code MC_CPT_Code,
MC.CPT_Modifier_1 MC_CPT_Modifier,
TO_CHAR(MC.First_DOS,'YYYYMMDD') MC_FDOS,
TO_CHAR(MC.Last_DOS,'YYYYMMDD') MC_LDOS,
MC.Charge MC_Line_Charge
FROM &1.Decision_Support DS,
&1.Medical_Claims MC
WHERE DS.Reprice_Status = 'U' AND
MC.CID = DS.CID
ORDER BY MC.ICN, MC.CID;
SPOOL OFF
You need to put your select statement in a parameterised function that returns a REF CURSOR. This is all well documented in the PL/SQL users guide.
Then you amend your SQL*PLUS script to call the function
VAR rc REFCURSOR
EXEC :rc := yr_function('&1')
PRINT rc
Cheers, APC
Similar Messages
-
File Ownership while executing sql script from stored procedure
We have a test_command.sql script which is spooling the result into a file. From database we have one Store Procedure(run_sql) which is
calling and executing the .sql script.
When we are calling the sql script directly from the database, i e SQL > @/dccops/test_command.sql it is creating the
file under the Ownership of OS user which is connected to the system.
The problem we are facing is when we are executing the stored procedure i e exec run_sql(), the file is creating under
Oracle User.
Could u please suggest me a solution inorder to create the output file under the user who is logged to the OS.First of all, your usage of IM speak is NOT appreciated. Please do not address anyone as if they were a 12-year old.
'Our Applcation is in C. So we have to call the procedure to run the sql script.'
This is just utter nonsense!
Oracle has Pro*C which allows Embedded SQL in C. There is also OCI (Oracle Call Interface) to call Oracle directly in C, and there is OCCI, to do the same in C++.
Apart from that, Oracle has Ole DB for Windows platforms, to allow for a .NET compatible interface to Oracle.
There is NO NEED AT ALL to call PL/SQL to run a SQL script.
Sybrand Bakker
Senior Oracle DBA -
Running a sql script from stored procedure
Hi everyone!
Has anybody tell me how to execute a sql script from a stored
procedure!
Thanks in advance!
Sasa>
Hi everyone!
Has anybody tell me how to execute a .sql file from a stored
procedure!
Thanks in advance!
Sasa Sorry, a .sql file!! -
MS SQL Server system stored procedures can't be migrated into Oracle 11g
During database migration from MS SQL Server 2008 to Oracle 11g R2, if the application stored procedure invokes the MS SQL Server system stored procedures (for example: sp_getapplock, sp_releaseapplock ....), these SQL server system stored procedures can't be transferred. See following migrated Oracle application stored procedure for example:
create or replace
PROCEDURE spPwSysID_GetNextID
v_ID OUT NUMBER,
iv_SysType IN NVARCHAR2 DEFAULT NULL ,
iv_Cnt IN NUMBER DEFAULT NULL
AS
v_SysType NVARCHAR2(50) := iv_SysType;
v_Cnt NUMBER(10,0) := iv_Cnt;
v_result NUMBER(10,0);
BEGIN
--SQL Server BEGIN TRANSACTION;
utils.incrementTrancount;
v_Systype := UPPER(v_Systype) ;
IF v_Cnt < 1 THEN
v_Cnt := 1 ;
END IF;
v_result :=sp_getapplock(v_Resource => v_Systype,
v_LockMode => 'Exclusive') ;
IF v_result >= 0 THEN
BEGIN
SELECT ID
INTO v_ID
FROM PWSYSID
WHERE SysType = v_SysType;
IF SQL%ROWCOUNT = 1 THEN
UPDATE PwSysID
SET ID = ID + v_cnt
WHERE SysType = v_SysType;
ELSE
BEGIN
INSERT INTO PwSysID
( ID, SysType )
VALUES ( v_cnt + 1, v_SysType );
v_ID := 1 ;
END;
END IF;
v_result :=sp_releaseapplock(v_Resource => v_Systype) ;
END;
ELSE
BEGIN
raise_application_error( -20002, 'Lock failed to acquire to generate Cityworks Id.' );
END;
END IF;
utils.commit_transaction;
END;During database migration from MS SQL Server 2008 to Oracle 11g R2, if the application stored procedure invokes the MS SQL Server system stored procedures (for example: sp_getapplock, sp_releaseapplock ....), these SQL server system stored procedures can't be transferred. See following migrated Oracle application stored procedure for example:
create or replace
PROCEDURE spPwSysID_GetNextID
v_ID OUT NUMBER,
iv_SysType IN NVARCHAR2 DEFAULT NULL ,
iv_Cnt IN NUMBER DEFAULT NULL
AS
v_SysType NVARCHAR2(50) := iv_SysType;
v_Cnt NUMBER(10,0) := iv_Cnt;
v_result NUMBER(10,0);
BEGIN
--SQL Server BEGIN TRANSACTION;
utils.incrementTrancount;
v_Systype := UPPER(v_Systype) ;
IF v_Cnt < 1 THEN
v_Cnt := 1 ;
END IF;
v_result :=sp_getapplock(v_Resource => v_Systype,
v_LockMode => 'Exclusive') ;
IF v_result >= 0 THEN
BEGIN
SELECT ID
INTO v_ID
FROM PWSYSID
WHERE SysType = v_SysType;
IF SQL%ROWCOUNT = 1 THEN
UPDATE PwSysID
SET ID = ID + v_cnt
WHERE SysType = v_SysType;
ELSE
BEGIN
INSERT INTO PwSysID
( ID, SysType )
VALUES ( v_cnt + 1, v_SysType );
v_ID := 1 ;
END;
END IF;
v_result :=sp_releaseapplock(v_Resource => v_Systype) ;
END;
ELSE
BEGIN
raise_application_error( -20002, 'Lock failed to acquire to generate Cityworks Id.' );
END;
END IF;
utils.commit_transaction;
END; -
How to execute .sql file in Stored Procedure?
Hi,
I have an urgent requirement, where i have to execute .sql file form Stored Procedure.
This .sql file will have set of update statement. I need to pass value to this update statement.
Kindly please help me.
Regards,
IrfanThis is required as part of Data Migration where i have to do 100 of table's update. Each time update table will defer, so its better to have in separate script file (.sql). Can u paste some sample/syntax to exceute .sql file from stored procedure. I am new to this PL/SQL.
How have you determined that it's "better" to have seperate scripts? I assume you mean the table name will "differ" (and not "defer" - I assume that's just because English isn't your first language? no problem - I think I understand what you're asking).
So what I think you're asking is that you have dynamic table names but each table needs to be updated in the same way?
Question: Why do you have tables with different names that all need the same process doing to them?
Assuming it's a valid requirement (and 99% of the time doing dynamic coding implies it's not).... you could use dynamic code, rather than 'scripts'...
e.g.
create procedure update_table(tbl_name varchar2) is
begin
execute immediate 'update '||tbl_name||' set lastupdate = null';
end;
As you haven't bothered to provide a database version, any example code/data or explanation of what you're actually doing, you're not going to get any detailed answer. Please do take the time to read the FAQ and post appropriate details so people can help you. -
Calling SQL * LOADER in stored procedure
Hi Experts,
Can we call sql*loader in stored procedures? . If yes , please let me know the syntax.
Any help will be highly appreciated.
Thanks.You can also use dbms_schedular to execute any shell or batch file - i guess ->
BEGIN
-- UNIX
DBMS_SCHEDULER.create_job(
job_name => 'unix_command_job',
job_type => 'EXECUTABLE',
number_of_arguments => 1,
job_action => '/bin/ls',
auto_drop => FALSE,
enabled => FALSE);
DBMS_SCHEDULER.set_job_argument_value('unix_command_job',1,'/tmp');
DBMS_SCHEDULER.set_attribute('unix_command_job', 'credential_name', 'TIM_HALL_CREDENTIAL');
DBMS_SCHEDULER.set_attribute('unix_command_job', 'destination', 'marge.localdomain:65001');
DBMS_SCHEDULER.enable('unix_command_job');
END;For details ->
http://www.oracle-base.com/articles/11g/SchedulerEnhancements_11gR1.php
http://www.oradev.com/dbms_scheduler.jsp
http://www.psoug.org/reference/dbms_scheduler.html
Regards.
Satyaki De. -
BI Publisher 11g - calling SQL Server 2005 stored procedure error
Hi experts
I have been calling succesfully an SQL server 2005 stored procedure for the data model of a BI publisher report in 10g, passing it a customerNo parameter.
EXEC [dbo].[usp_WelcomeLettersConsumerNo]
@CustomerNo = :sCustomerNo
However it does not work in 11g I get the error:
[Hyperion][SQLServer JDBC Driver][SQLServer]Incorrect syntax near the keyword 'is'.
which is frustrating as there is no 'is' in the statement (perhaps it is picking up :s?) - I wonder does anyone know if there has been a change in 11g that may be causing this?
cheers
TimHi experts
I have been calling succesfully an SQL server 2005 stored procedure for the data model of a BI publisher report in 10g, passing it a customerNo parameter.
EXEC [dbo].[usp_WelcomeLettersConsumerNo]
@CustomerNo = :sCustomerNo
However it does not work in 11g I get the error:
[Hyperion][SQLServer JDBC Driver][SQLServer]Incorrect syntax near the keyword 'is'.
which is frustrating as there is no 'is' in the statement (perhaps it is picking up :s?) - I wonder does anyone know if there has been a change in 11g that may be causing this?
cheers
Tim -
What is the data dictionary that stores the SQL text of stored procedures?
I am handling both Oracle 8i on IBM AIX 5L and Oracle9i on SUN Soliars 8 /9.
What is/are the data dictionary tables, or v$ views that store the SQL text of stored procedured and triggers?
Thank you in advance!If the procedures are not wrapped, you can view them in the dba/all/user_source view. Trigger bodies can be seen in dba/all/user_triggers view.
Message was edited by:
Daniel Fink -
Returning SQL cursor from Stored Procedure
Hi,
I have a query regarding returning sql cursor from stored procedure to java in oracle 11g.
I want to query some data ex: my query returns A, B, C. Also, now I want to query some other data ex: D, E, F. Now I want to return this data as an sql cursor as a single row . Example: A,B,C,D,E,F. Is it possible to return/create a cursor in stored procedure?
assume both query returns equal number of rows.. however both are not related to each other..RP wrote:
Hi,
I have a query regarding returning sql cursor from stored procedure to java in oracle 11g.
I want to query some data ex: my query returns A, B, C. Also, now I want to query some other data ex: D, E, F. Now I want to return this data as an sql cursor as a single row . Example: A,B,C,D,E,F. Is it possible to return/create a cursor in stored procedure?
assume both query returns equal number of rows.. however both are not related to each other..It sounds like what you need is a ref cursor.
First thing to remember though is that cursors do not hold any data (see: {thread:id=886365})
In it's simplest form you would be creating a procedure along these lines...
SQL> create or replace procedure get_data(p_sql in varchar2, p_rc out sys_refcursor) is
2 begin
3 open p_rc for p_sql;
4 end;
5 /
Procedure created.
SQL> var rc refcursor;
SQL> exec get_data('select empno, ename, deptno from emp', :rc);
PL/SQL procedure successfully completed.
SQL> print rc;
EMPNO ENAME DEPTNO
7369 SMITH 20
7499 ALLEN 30
7521 WARD 30
7566 JONES 20
7654 MARTIN 30
7698 BLAKE 30
7782 CLARK 10
7788 SCOTT 20
7839 KING 10
7844 TURNER 30
7876 ADAMS 20
7900 JAMES 30
7902 FORD 20
7934 MILLER 10
14 rows selected.
SQL> exec get_data('select deptno, dname from dept', :rc);
PL/SQL procedure successfully completed.
SQL> print rc
DEPTNO DNAME
10 ACCOUNTING
20 RESEARCH
30 SALES
40 OPERATIONS
50 IT SUPPORTWhich takes an SQL statement (as you said that both your queries were unrelated), and returns a ref cursor, and then your Java code would fetch the data using that cursor.
Now, as for getting your rows to columns and combining two queries that do that... something along these lines...
SQL> select * from x;
C
A
B
C
SQL> select * from y;
C
D
E
F
SQL> ed
Wrote file afiedt.buf
1 select x.col1, x.col2, x.col3
2 ,y.col1 as col4
3 ,y.col2 as col5
4 ,y.col3 as col6
5 from (
6 select max(decode(rn,1,col1)) as col1
7 ,max(decode(rn,2,col1)) as col2
8 ,max(decode(rn,3,col1)) as col3
9 from (select col1, rownum rn from (select * from x order by col1))
10 ) x
11 cross join
12 (
13 select max(decode(rn,1,col1)) as col1
14 ,max(decode(rn,2,col1)) as col2
15 ,max(decode(rn,3,col1)) as col3
16 from (select col1, rownum rn from (select * from y order by col1))
17* ) y
SQL> /
C C C C C C
A B C D E F... will do what you ask. For further information about turning rows to columns read the FAQ: {message:id=9360005} -
Requirements of SQL Server 2005 Stored Procedures to Develop Crystal Report
Hi All,
I want to learn how to create crystal report off of SQL Server 2005 Stored Procedure. So anybody please let me know from where I can download the documentation on "Requirements of SQL Server 2005 Stored Procedures for crystal report.
I am using Crystal Report XI. Any help is greatly appreciated.
Thank You.Hello,
When CR uses Stored Porcedures we only look at the last SELECT statement. We can't use TMP tables because they are owned by the system and not the user. Even though you created them under your logon credentials you are not the actual owner. Or so I have found so far.... CR does not have permissions to get to those temp tables. If you can find out dynamically what the table names are called then it may work. I don't have a sample but it has the usual table info with a random GUID or temp name, really long, and changes every time.
What should work is create a real table, not one of MS's tempTables and then push all your data to that table and then the last select statement returns all of your data from that temp table:
SELECT * FROM MYTEMPTABLE.DBO.TABLE.
Then CR should ahve no issues.
It may be that the JDBC driver has problems. Test it using OLE DB or ODBC.
Thanks again
Don -
.sql program VS stored procedure
Hi,
We are in the process of migrating a lot of .sql files into Oracle warehouse Builder programs.
So most of them will be converted to stoted procedure, Before committing anything , Just a quick question ..
Can there be any statements which is ONLY possible in .SQL files (OS level files)
and which is NOT possible in Stored procedure ?
cheers
RanjeeshDepends on what kind of code you have in those SQL-script files.
SQL*Plus commands cannot be used in PL/SQL procedure, e.g. COLUMN-formatting, environment SETting, and BREAK etc.
There should not be any problem with converting DMLs. But, in case of DDLs you will have to use dynamic PL/SQL. -
Pass unicode data in SQL Server 2008 stored procedure parameter
Hi,
I want to pass unicode data in a SQL stored procedure. But I am not sure that how to append N with NVarchar datatype.
For example I Create a table LocalizationTest and wants to insert a few records.
Create table LocalizationTest
Field1 NVarchar(255)
INSERT INTO LocalizationTest
VALUES(N'123 Illini Dr, 東皮奧里亞, 8989')
the above given statement works.
To explain it more , script A works but script B does not work.
DECLARE @X NVARCHAR(255)
[A]
SET @X=N '123 Illini Dr, 東皮奧里亞, 8989'
INSERT INTO LocalizationTest
VALUES(@X)
[B]
SET @X= '123 Illini Dr, 東皮奧里亞, 8989'
INSERT INTO LocalizationTest
VALUES(@X)
What is the correct way to execute script B because @X will be passed in a SQL Stored Procedure?
Thanks
Sharma M.If you do not pass the value as a Unicode value there is nothing left of the Unicode characters but question marks. Once this has happened, AFAIK there is no way to undo it (other than resetting the value as Unicode characters again).
Affirmative.
Demo - This is what happens if you convert UNICODE (nvarchar) to varchar with implicit conversion (try to force 2 bytes into one byte).
3F hex is '?'.
CREATE TABLE #LocalizationTest (Field1 VARCHAR(255))
INSERT INTO #LocalizationTest
VALUES(N'123 Illini Dr, 東皮奧里亞, 8989')
DECLARE @X NVARCHAR(255), @dSQL NVARCHAR(MAX)
SET @X=N'123 Illini Dr, 東皮奧里亞, 8989'
INSERT INTO #LocalizationTest VALUES(CONVERT(NVARCHAR(255),@X))
SET @dSQL = N'INSERT INTO #LocalizationTest VALUES(N'''+@X+''')'
PRINT @dSQL
EXEC sp_ExecuteSQL @dSQL
SELECT *, Field1Bin=convert(binary(30), Field1) FROM #LocalizationTest
DROP TABLE #LocalizationTest
123 Illini Dr, ?????, 8989 0x31323320496C6C696E692044722C203F3F3F3F3F2C203839383900000000
123 Illini Dr, ?????, 8989 0x31323320496C6C696E692044722C203F3F3F3F3F2C203839383900000000
123 Illini Dr, ?????, 8989 0x31323320496C6C696E692044722C203F3F3F3F3F2C203839383900000000
Kalman Toth Database & OLAP Architect
SQL Server 2014 Design & Programming
New Book / Kindle: Exam 70-461 Bootcamp: Querying Microsoft SQL Server 2012 -
Calling sql script in plsql procedure
Hello,
I have a sql script named mytest.sql and i want to execute this from a stored procedure.
following is the contents of this script
spool d:\mytestsql.txt
select * from tab;
spool off
Actually i want my sql script to run daily to export some tables data.
I can execute this script from a sql prompt but i want to run it from enterprise manager.
I am using oracle 10gR2 on windows2000 system.
Any idea about scheduling the sql script to run automatically??
How to execute this sql script from a plsql procedure??
ThanksHi all,
Thanks for all the replies. I have found the solution with external procedures.
Following is the complete step by step guide.
1. Create the OSCommand Java Class using the following statement:
connect as any user:
create or replace and compile java source named oscommand as
import java.io.*;
public class OSCommand{
public static String Run(String Command){
try{
Runtime.getRuntime().exec(Command);
return("0");
catch (Exception e){
System.out.println("Error running command: " + Command +
"\n" + e.getMessage());
return(e.getMessage());
2. Create the following Wrapper Function using the following statement:
CREATE or REPLACE FUNCTION OSCommand_Run(Command IN STRING)
RETURN VARCHAR2 IS
LANGUAGE JAVA
NAME 'OSCommand.Run(java.lang.String) return int';
3. connect as sys
Execute dbms_java.grant_permission( 'FKHALID','SYS:java.io.FilePermission', '<<ALL FILES>>','execute');
execute dbms_java.grant_permission( 'FKHALID','SYS:java.lang.RuntimePermission', 'writeFileDescriptor', '*' );
execute dbms_java.grant_permission( 'FKHALID','SYS:java.lang.RuntimePermission', 'readFileDescriptor', '*' );
commit;
note: here fkhalid is the oracle user.
connect as fkhalid user:
Declare
expdp_cmd Varchar2(2000);
Begin
expdp_cmd := OSCommand_Run('cmd /c sqlplus fkhalid@mtcedwt/pwd @d:\ORA_DUMPS\mydbexp.sql');
DBMS_OUTPUT.Put_Line(expdp_cmd);
End;
In Unix
Set Serverout On
Declare
x Varchar2(2000);
Begin
x := OSCommand_Run('/home/test/myoscommand.sh')
DBMS_OUTPUT.Put_Line(x);
End;
I will check the dbms_scheduler also and will let you know the results.
Thanks -
BOBJ DI 12.2.2.1| SQL Transform call stored procedure on MSSQL 2008 FAIL
Hello everyone!
Sorry for my bad english.
in my job is one dataflow with sql transform, query and target table (LOG).
SQL Text is :
EXEC dbo.ProcName
in this SP next content:
BEGIN TRY
CREATE TABLE #t(...)
INSERT INTO #t SELECT (...)
INSERT INTO Table1
SELECT(...) FROM #t
ENDTRY
BEGIN CATCH
SELECT (row with error number, error message)
END CATH
IF NOERROR SELECT (row with no error and rows affected)
When I run it from Management Studio all is OK. Data is successfully inserted into Table1and rRow with rowcount was inserteg into LOG.
But When I run it in Job on JobServer exact row inserting into LOG BUT! no data inserting into Table1. and rowcount is equal in both cases.
What's happening?
Help please.for calling a stored procedure from DI, SQL Transform is not the correct way of doing it, the better option is to import the stored procedure in SQL Server Datastore and calling in a script or in a mapping depending on what that SP is doing
to import a stored procedure in a DataStore, expand the Datastore select function node and click Import by name, in the type select function and enter the stored procedure or function name
for DI both Stored Procedure and Functions are treated as Functions -
Dynamic SQL and Oracle stored procedures
Does anybody has any experience with invoking an Oracle stored procedures
with output parameters, using dynamic SQL from Forte?
Thanks,
DimitarI would be interested. We are currently using a homegrown DataMapper architecture with the Microsoft OracleClient. I would like to move to ODP.Net once a production version supporting ADO.Net 2.0 is available. After that, I would then like to look at using an off the shelf persistence framework such as EntitySpaces, NHibernate or IdeaBlade's DevForce.
Maybe you are looking for
-
Can no longer connect to Airport Express with upgrade to iTunes 10.1
Since I upgraded to iTunes 10.1 I can no longer connect to my Airport Express (unknown error-15000). Another computer on my betwork running an older version of iTunes still works on the Airport Express. Any ideas? I have tried to uninstall and reinst
-
How to install SMP Kernel on RHEL 4
Hi all, I am installing 2 Node RAC on VMWare on RHEL 4. For which i need to have SMP Kernel installed. As of now this is what i have. uname -a Linux abc.xyz.com 2.6.9-5.EL #1 Wed Jan 5 19:22:18 EST 2005 i686 i686 i386 GNU/Linux Kindly guide me to the
-
InDesign Folio Builder Sign-In Failure.
I was wondering if anyone else had a similar issue when trying to log in to their DPS account from the Folio Builder tab within InDesign. I have downloaded and installed the latest versions of updates for the Folio Builder and Producer and am running
-
Managed Files still attached to deleted bundle
I have some files that were part of a File Bundle I have deleted. Unfortunately the files still appear under Tools, FileList and appear to still think they are in the bundle I deleted. They do not appear when I search for Orphaned Managed Files and a
-
Help - error message after iTunes update
I have a Windows 7 PC I updated iTunes about four days ago and got an error message. What should I do to correct this annoying issue? AppleSyncNotifier.exe - Entry Point Not Found The Procedure entry point xmlTextTeaderName could not be located in th