Passing UDT as parameter to Anonymous block in C# code throws error
Hi Gurus,
Can't seem to make it work when UDT is involved.
I have a proc with the ff signature:
MySchema.MyProc(p_param1 IN OUT MyUDT, p_output OUT SYS_REFCURSOR)
Now I have generated a C# class to map my UDT. I created a pl/sql block below:
string sql = "BEGIN " +
"MySchema.MyProc(:1, :2); " +
"END;";
MyUDT prm = CreateMyUDT();
cmd.CommandText = sql;
cmd.Parameters.Add(":1", OracleDbType.Object, System.Data.ParameterDirection.InputOutput).Value = prm;
cmd.Parameters.Add(":2", OracleDbType.RefCursor, System.Data.ParameterDirection.Output);
cmd.ExecuteReader() or cmd.ExecuteNonQuery() both throws "*Invalid Parameter binding" error*.
Any suggestion how I can resolve this error pls...
regards.
I am not sure about the original thread request, but I have found some valuable information from Mark William's site. He wrote a book on ODP.NET which is also a very good and helpful book.
http://oradim.blogspot.com/2007/04/odpnet-tip-anonymous-plsql-and.html
http://www.cheshamdbs.com/
Hope it helps you.
Similar Messages
-
Need help displaying item based on pl/sql anonymous block
This is probably something really simple but I'm stuck.....
On purchase order, I want to show related parent project name and ID. What is the best way to do it? I have created a region based on pl/sql anonymous block, and that works, but the data is above where I want it. I want the project name and ID to show up in the region w/ all the other fields.
I have created an item in the region that has other form fields, item is based on pl/sql anonymous block, w/ same code as above region, and the item doesn't find the data. What's the difference? Is it because the item doesn't save state? In order to choose for the item to be based on pl/sql anon block, APEX made me choose Display as Text (based on PLSQL, does not save state).
Please see this picture:
http://farm3.static.flickr.com/2391/2658673285_04f157a3fa_o.png
thanks!
~Darbythis is weird.. Now it is working. I didn't change anything! What the heck?
http://farm3.static.flickr.com/2010/2659557520_73e54b67ea_o.png -
hi friends
I am trying to develop anonymous block which display the message on screen like "hello world" "today is SYSDATE" and "Tommorow is SYSDATE+1".For that i try to develop anonymous block but it shows me error..so friends can you help me out with this...
set SERVEROUTPUT on
declare
p_text varchar2 DEFAULT 'hello world';
P_date date Default sysdate;
P_next_date date default sysdate+1;
begin
DBMS_OUTPUT.PUT_LINE (||P_text);
DBMS_OUTPUT.PUT_LINE ('today is:'||P_date);
DBMS_OUTPUT.PUT_LINE ('Tommorrow is:'||p_next_date);
end;
thanks in advance
rommyHi, Rommy,
Always format your code. Indent to show the major sections (DECLARE, BEGIN, etc.)
Type these 6 characters
{code}
(small letters only, inside curly brackets) before and after formatted text, to preserve spacing when posting on this site.
DECLARE
p_text VARCHAR2 (50) DEFAULT 'hello world';
P_date DATE DEFAULT SYSDATE;
P_next_date DATE DEFAULT SYSDATE + 1;
BEGIN
DBMS_OUTPUT.PUT_LINE (P_text);
DBMS_OUTPUT.PUT_LINE ('today is: ' || TO_CHAR (P_date, 'Dy DD-Mon-YYYY'));
DBMS_OUTPUT.PUT_LINE ('Tommorrow is: ' || TO_CHAR (p_next_date, 'Dy DD-Mon-YYYY'));
END;
/When you declare a VARCHAR2 variable, you have to specify the maximum length.
The || operator is used between two string expressions; it looks like you forgot the first operand in one place.
Using a DATE where a VARCHAR2 is expected (as an operand to ||, for example) is not technically an error, but it's bad practice. Use TO_CHAR to create a string in whatever format you want. -
Pass values to Guid collection/array parameter for anonymous pl/sql block
The following code pops the System.ArgumentException: Invalid parameter binding
Parameter name: p_userguids
at Oracle.DataAccess.Client.OracleParameter.GetBindingSize_Raw(Int32 idx)
at Oracle.DataAccess.Client.OracleParameter.PreBind_Raw()
at Oracle.DataAccess.Client.OracleParameter.PreBind(OracleConnection conn, IntPtr errCtx, Int32 arraySize)
at Oracle.DataAccess.Client.OracleCommand.ExecuteNonQuery()
Any help or advice ?
anonymous pl/sql block text:
DECLARE
TYPE t_guidtable IS TABLE OF RAW(16);
p_userguids t_guidtable;
BEGIN
DELETE testTable where groupname=:groupname;
INSERT INTO testTable (userguid, groupname)
SELECT column_value, :groupname FROM TABLE(p_userguids);
END;
c# code:
public static void SetGroupUsers(string group, List<Guid> users)
OracleConnection conn = Database.ConnectionEssentus;
try
conn.Open();
OracleCommand sqlCmd = new OracleCommand();
sqlCmd.CommandText = sqls["SetGroupUsers"]; // above anonymous block
sqlCmd.Connection = conn;
sqlCmd.BindByName = true;
OracleParameter p_guidCollection = sqlCmd.Parameters.Add("p_userguids", OracleDbType.Raw);
p_guidCollection.Size = users.Count;
p_guidCollection.CollectionType = OracleCollectionType.PLSQLAssociativeArray;
p_guidCollection.UdtTypeName = "t_guidtable";
p_guidCollection.Value = users.ToArray();
sqlCmd.Parameters.Add("groupname", OracleDbType.Varchar2, 30).Value = group;
sqlCmd.ExecuteNonQuery();
catch(Exception ex)
System.Diagnostics.Debug.WriteLine(ex.ToString());
finally
conn.Close();
}New question,
How can I select records using "in" condition clause likes the following sentence?
SELECT userguid, firstname, lastname FROM UserTable WHERE userguid in (SELECT column_value FROM TABLE(p_userguids))
I tried using PIPE ROW like this, but ORACLE said "PLS-00629: PIPE statement cannot be used in non-pipelined functions"
FOR i in p_userguids.first .. p_userguids.last
LOOP
SELECT userguid, firstname, lastname INTO l_userrecord FROM UserTable WHERE userguid=p_userguids(i);
PIPE ROW(l_userrecord);
END LOOP; -
Pass parameter to another block
I try to pass parameter to another block. but i have error message.
error:PL/SQL: ORA-00904: "C1DATA_REF"."c": invalid identifier.
Would you help me?
___________________________+++my code+++
CREATE OR REPLACE PROCEDURE GETID
(a IN TEST.COUNTRY%TYPE,
b IN TEST.STATE%TYPE) AS
V_ID TEST2.c%TYPE;
CURSOR C1_DATA IS
SELECT a,b,c FROM TESTSURVEYUNITS WHERE COUNTRY=a
AND STATE=b ;
BEGIN
BEGIN
FOR C1DATA_REF IN C1_DATA LOOP
DBMS_OUTPUT.PUT_LINE ('SVU_ID IS:' || C1DATA_REF.c);
END LOOP;
END;
BEGIN
SELECT e,f,g,c FROM TEST2 WHERE SVU_ID=C1DATA_REF.c;
DBMS_OUTPUT.PUT_LINE('PART 2'||C1DATA_REF.c||C1DATA_REF.e);
END;
END;Here it is reformatted. The SELECT statement in the second block won't work because there is no INTO clause and also because the cursor for loop in the previous block is out of scope. The loop has fetched all of its rows and has completed. What are you trying to do with the second select statement?
CREATE OR REPLACE
PROCEDURE GETID (a IN TEST.COUNTRY%TYPE
,b IN TEST.STATE%TYPE) AS
V_ID TEST2.c%TYPE;
CURSOR C1_DATA IS
SELECT a,b,c
FROM TESTSURVEYUNITS
WHERE COUNTRY=a
AND STATE=b ;
BEGIN
BEGIN
FOR C1DATA_REF IN C1_DATA LOOP
DBMS_OUTPUT.PUT_LINE ('SVU_ID IS:' || C1DATA_REF.c);
END LOOP;
END;
BEGIN
SELECT e,f,g,c
FROM TEST2
WHERE SVU_ID=C1DATA_REF.c;
DBMS_OUTPUT.PUT_LINE('PART 2'||C1DATA_REF.c||C1DATA_REF.e);
END;
END; -
Calling a function which has a CLOB parameter via an anonymous block.
OK,
we are moving a lot of exports currently done by Crystal to just be done by stored procs.
So we have a load of existing, some extremely length SQL statements used for these exports.
IN the exports, we have meaningful column headings, so we have a 'lookup' file where all the column names are listed with the desired column name text listed against it.
So - to make our lives easier(i thought) , I have written a Oracle function to extract al;l of the column names as a list (see below).
It works fine except for when I am trying to pass in a SQL treatment that is longer than 4000 character.
What I want to be able to do is simply have an anonymous block that callls my function, I will be running this via SQL explorer.
Something like......
DECLARE
theSQL CLOB;
BEGFIN
theSQL := 'SELECT * FROM ORDERS WHERE 1=0';
SELECT GET_COLUNS_AS_LIST( theSQL, 0 ) FROM DUAL;
END;
However, when I run this I get the error................
PLS-00428: an INTO clause is expected in this SELECT statement
06550. 00000 - "line %s, column %s:\n%s"
*Cause: Usually a PL/SQL compilation error.
If I hard code the SQL like this, SELECT GET_COLUNS_AS_LIST( 'SELECT * FROM ORDERS WHERE 1=0', 0 ) FROM DUAL; all is well.
Also, I am going to need to be able to pass in SQL ststement longer that 4000 characters as weel so please bear that in mind.
I am not an Oracle guy, so I guess I am missing something fundamental - Please enlighten me with regards to this.
Any help extremely appreciated.
CREATE OR REPLACE FUNCTION GET_COLUNS_AS_LIST( P_SQL IN VARCHAR2, Add_Equals_Sign Number := 0)
RETURN CLOB
IS
fResult VARCHAR2(32000);
HNDL NUMBER;
d NUMBER;
colCount INTEGER;
i INTEGER;
rec_tab DBMS_SQL.DESC_TAB;
cCRLF VARCHAR(2) := CHR(13) || CHR(10);
LONG_SQL dbms_sql.varchar2s;
n INTEGER;
l INTEGER;
u INTEGER;
StartPos INTEGER;
BEGIN
--INITIIALISE RESULT
fResult := '';
HNDL := DBMS_SQL.OPEN_CURSOR;
l := Length( P_SQL );
u := ( l / 1000 ) + 1;
FOR n IN 1..u
LOOP
StartPos := ( n - 1 ) + 1;
LONG_SQL( n ) := SubStr( P_SQL, StartPos, 1000 );
END LOOP;
if HNDL <> 0 THEN
DBMS_SQL.PARSE ( c => HNDL,
statement => LONG_SQL,
lb => 1,
ub => u,
lfflg => false,
language_flag => DBMS_SQL.NATIVE );
--DBMS_SQL.PARSE( HNDL, P_SQL, DBMS_SQL.NATIVE);
d := DBMS_SQL.EXECUTE( HNDL );
DBMS_SQL.DESCRIBE_COLUMNS( HNDL, colCount, rec_tab);
FOR i in 1..colCount
LOOP
IF Add_Equals_Sign > 0 AND i > 1 THEN
fResult := ltrim( fResult || '=' || cCRLF || UPPER( rec_tab( i ).col_name ), cCRLF );
ELSE
fResult := ltrim( fResult || cCRLF || UPPER( rec_tab( i ).col_name ), cCRLF );
END IF;
END LOOP;
IF Add_Equals_Sign > 0 THEN
fResult := fResult ||'=';
END IF;
ELSE
fResult := '!!COULD NOT OPEN CURSOR!!';
fResult := P_SQL;
END IF;
RETURN fResult;
--Tidy Up
DBMS_SQL.CLOSE_CURSOR(HNDL);
Return 'EGG';
END;
--EXAMPLE USAGE
--Select GET_COLUNS_AS_LIST
--Select * from SALES_TYPE
--', 1) FROM DUAL;So I have ended up with this.
When I next get some time, I'd like to be able to strip out the table and simply output the results to an SQL Developer script window without having to go through the table.
Now this works - but if you see that I am doing something wrong - please point it out.
Many thanks,
Ant
CREATE OR REPLACE FUNCTION GET_COLUNS_AS_LIST( P_SQL IN CLOB, Add_Equals_Sign Number := 0)
RETURN VARCHAR2
IS
fResult VARCHAR2(32000);
HNDL NUMBER;
d NUMBER;
colCount INTEGER;
i INTEGER;
ChunkSize INTEGER;
rec_tab DBMS_SQL.DESC_TAB;
cCRLF VARCHAR(2) := CHR(13) || CHR(10);
LONG_SQL dbms_sql.varchar2s;
n INTEGER;
l INTEGER;
u INTEGER;
StartPos INTEGER;
BEGIN
--INITIIALISE RESULT
HNDL := 0;
ChunkSize := 4;
fResult := '';
--fResult := fResult|| 'A';
HNDL := DBMS_SQL.OPEN_CURSOR;
--l := Length( P_SQL );
l := dbms_lob.getLength( P_SQL );
--l := 50;
u := Round( l / ChunkSize ) + 1;
--fResult := fResult|| 'B';
FOR n IN 1..u
LOOP
StartPos := ( ( n - 1 ) * ChunkSize ) + 1;
IF StartPos = 0 THEN
StartPos := 1;
END IF;
--LONG_SQL( n ) := SubStr( P_SQL, StartPos, ChunkSize );
LONG_SQL( n ) := DBMS_LOB.SUBSTR( P_SQL, ChunkSize, StartPos );
END LOOP;
--fResult := fResult|| 'C';
if HNDL <> 0 THEN
DBMS_SQL.PARSE ( c => HNDL,
statement => LONG_SQL,
lb => 1,
ub => u,
lfflg => false,
language_flag => DBMS_SQL.NATIVE );
--DBMS_SQL.PARSE( HNDL, P_SQL, DBMS_SQL.NATIVE);
d := DBMS_SQL.EXECUTE( HNDL );
DBMS_SQL.DESCRIBE_COLUMNS( HNDL, colCount, rec_tab);
--fResult := fResult|| 'D';
FOR i in 1..colCount
LOOP
IF Add_Equals_Sign > 0 AND i > 1 THEN
fResult := ltrim( fResult || '=' || cCRLF || UPPER( rec_tab( i ).col_name ), cCRLF );
ELSE
fResult := ltrim( fResult || cCRLF || UPPER( rec_tab( i ).col_name ), cCRLF );
END IF;
END LOOP;
IF Add_Equals_Sign > 0 THEN
fResult := fResult ||'=';
END IF;
ELSE
fResult := '!!COULD NOT OPEN CURSOR!!';
END IF;
RETURN fResult;
--Tidy Up
IF HNDL <> 0 THEN
DBMS_SQL.CLOSE_CURSOR(HNDL);
END IF;
END;
-- !!!!HOW TO USE THIS FUNCTION!!!!
BEGIN
EXECUTE IMMEDIATE ('DROP TABLE RPT_COLNAME_LOOKUPS;');
COMMIT;
EXECUTE IMMEDIATE ('CREATE TABLE RPT_COLNAME_LOOKUPS( COLUMN_NAME CLOB );');
COMMIT;
EXCEPTION WHEN OTHERS THEN NULL;
END;
DECLARE
theSQL Clob;
myresult CLOB;
BEGIN
--CLEAR OUT PREVIOUS RWS
DELETE FROM RPT_COLNAME_LOOKUPS; COMMIT;
--ASSIGN THE SQL TO RUN IT FOR
theSQL := '
SELECT
EVENT.EVENT_ID AS COCK_SUCKER,
EVENT.EVENT_CODE, BLAH, BLAH, VERY LONG SQL STATEMENT';
--CALL THE FUNCTION PASSING IN THE SQL AND IF I WANT THE = OR NOT
SELECT GET_COLUNS_AS_LIST( theSQL, 1 ) INTO myresult FROM DUAL;
--INSERT THE RESULTS INTO A TABLE SO WE CAN GRAB THEM
INSERT INTO RPT_COLNAME_LOOKUPS SELECT myresult FROM DUAL;
COMMIT;
END;
--THEN LOOK AT THE COLUMNS NAMES IN THIS TABLE
--SELECT * FROM RPT_COLNAME_LOOKUPS;
--############################################################################# -
INVALID CURSOR - Anonymous Block calling Cursor in function
I am getting an error when trying to call my cursor.
CREATE OR REPLACE PACKAGE tax_update
AS
TYPE gencur IS ref cursor;
FUNCTION tax_sf
p_state IN bb_tax.state%type,
p_thecursor IN OUT gencur
RETURN NUMBER;
END;
CREATE OR REPLACE PACKAGE BODY tax_update
AS
FUNCTION tax_sf
p_state IN bb_tax.state%type,
p_thecursor IN OUT gencur
RETURN NUMBER
IS
lv_taxrate NUMBER;
BEGIN
OPEN p_thecursor FOR
SELECT taxrate
FROM bb_tax
WHERE state = p_state;
RETURN lv_taxrate;
END;
END;
DECLARE
tax_cur tax_update.gencur;
rec_tax bb_tax%rowtype;
BEGIN
LOOP
FETCH tax_cur INTO rec_tax;
EXIT WHEN tax_cur%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(rec_tax.taxrate);
END LOOP;
END;
DECLARE
ERROR at line 1:
ORA-01001: invalid cursor
ORA-06512: at line 6Assignment is to create a package that will hold tax rates by state in a packaged cursor. The package will contain a function that can receive a 2 character state abbr. as an argument and find a match in the cursor and return the tax rate for tha tstate. An anonymous block will test the function with state of NC.
Can anyone assist?You would need to call the function to open the cursor before you try to fetch from the cursor
DECLARE
tax_cur tax_update.gencur;
rec_tax bb_tax%rowtype;
l_some_number number;
BEGIN
l_some_number := tax_update.tax_sf( <<some state parameter>>, tax_cur );
LOOP
FETCH tax_cur INTO rec_tax;
EXIT WHEN tax_cur%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(rec_tax.taxrate);
END LOOP;
END;A couple of points, though.
1) Your function returns a NUMBER but that NUMBER will always be NULL. It seems rather unlikely that this is really what you want. It would seem to make more sense for the function to return the cursor rather than returning a superfluous number.
2) Your function requires a `bb_tax.state%type` parameter. But your anonymous block doesn't seem to have any concept of a state so I'm not sure what you want to pass in there.
3) Looking at the code, it seems a bit odd that your cursor returns a single column of data. If a state can have multiple rates, wouldn't you need to select some additional criteria in order to figure out which sort of tax each row represents or to otherwise differentiate different rows? If a state can only have a single tax rate, it makes no sense to open a cursor that is only going to ever return a single row.
4) There is no need to declare your own weak ref cursor type (tax_update.gencur). You can just use the Oracle built-in type SYS_REFCURSOR.
Justin -
Getting value with an anonymous block using ODP
Hi all!
I have a problem I hope someone can help me with. I believe it to be a minor one. I am trying to imbed an anonymous block into my .net app and use it dynamically to get a value from the database depending on the values in a tables. Since my procedure is quite large I am displaying a small example proc for simplicity purposes. Basically I want to execute an anonymous block from my app that will return a value (not a row or rows) from the database. The code is below:
Private Sub test()
Dim cn As New OracleConnection(profileString)
Try
Dim sb As New System.Text.StringBuilder
sb.Append("Declare ")
sb.Append("v_maxnum varchar2(6); ")
sb.Append("Begin ")
sb.Append("Select max(to_number(email_address_id)) into ")
sb.Append("v_maxnum from CVWH14_CDRV_TEST.EMAIL_ADDRESS_TBL; ")
sb.Append("dbms_output.put_line(v_maxnum); ")
sb.Append("Exception ")
sb.Append("When Others ")
sb.Append("Then ")
sb.Append("dbms_output.put_line('Program run errors have occurred.'); ")
sb.Append("End; ")
Dim cmd As New OracleCommand(sb.ToString, cn)
With cmd
cmd.CommandType = CommandType.Text
Dim parm As New OracleParameter
parm.ParameterName = "v_maxnum"
parm.OracleType = OracleType.VarChar
parm.Direction = ParameterDirection.Output
parm.Size = 6
cmd.Connection.Open()
Dim ret As Object = cmd.ExecuteScalar()
Dim res As String = cmd.Parameters.Item(0).Value.ToString -- **Error is occuring here**
cmd.Connection.Close()
cmd.Dispose()
End With
Catch ex As Exception
MessageBox.Show(ex.Message, "Error")
'End If
If cn.State = ConnectionState.Open Then
cn.Close()
End If
End Try
End Sub
The exception error reads "Invalid Index 0 for this OracleParameterCollection with Count=0."
If I can figure out how to get a parameter value from the database via the anonymous block, I can apply the logic to the real application. Any help or direction I could receive would be greatly appreciated. Thanks for reading this post!Thank you for responding. The code that I posted was just one of many ways I have tried. I retried the proc making just 2 changes:
Private Sub test()
Dim cn As New OracleConnection(profileString)
Try
Dim sb As New System.Text.StringBuilder
sb.Append("Declare ")
sb.Append("v_maxnum varchar2(6); ")
sb.Append("Begin ")
sb.Append("Select max(to_number(email_address_id)) into ")
sb.Append("v_maxnum from CVWH14_CDRV_TEST.EMAIL_ADDRESS_TBL; ")
sb.Append("dbms_output.put_line(:v_maxnum); ") -- !Changed this to a bind variable!
sb.Append("Exception ")
sb.Append("When Others ")
sb.Append("Then ")
sb.Append("dbms_output.put_line('Program run errors have occurred.'); ")
sb.Append("End; ")
Dim cmd As New OracleCommand(sb.ToString, cn)
With cmd
cmd.CommandType = CommandType.Text
Dim parm As New OracleParameter
parm.ParameterName = ":v_maxnum" -- !Changed this to a bind variable!
parm.OracleType = OracleType.VarChar
parm.Direction = ParameterDirection.Output
parm.Size = 6
cmd.Connection.Open()
Dim ret As Object = cmd.ExecuteScalar() -- !The error is now occuring here!
Dim res As String = cmd.Parameters.Item(0).Value.ToString
cmd.Connection.Close()
cmd.Dispose()
End With
Catch ex As Exception
MessageBox.Show(ex.Message, "Error")
If cn.State = ConnectionState.Open Then
cn.Close()
End If
End Try
End Sub
I am now getting the error message "Not all variables bound". Any more help or direction that you could throw my way would be greatly appreciated. -
Output parameter in plsql Block fails
Hello. I am testing using an anonymous Plsql block with one in and out parameter. The in parameter work fine but when I add the out, the plsql block fails.
This is my environment on a Windows 7 client attaching to a Solaris server. I am using Powershell 3.0, but it is very similar to #c. I have a .net framework of 4.5.
PS L064217> $GAC = $Env:Oracle_Home + "\" + "ODP.NET\bin\4\Oracle.DataAccess.dll"
PS L064217> [Void] [Reflection.Assembly]::LoadFile($Gac)
PS L064217> [Reflection.Assembly]::LoadFile($Gac)
GAC Version Location
True v4.0.30319 C:\windows\Microsoft.Net\assembly\GAC_64\Oracle.DataAccess\v4.0_4.112.3.0__89b4
SQL*Plus: Release 11.2.0.3.0 Production on Wed Nov 28 19:09:57 2012
Copyright (c) 1982, 2011, Oracle. All rights reserved.
Connected to:
Oracle Database 11g Enterprise Edition Release 11.2.0.2.0 - 64bit Production
With the Partitioning, OLAP, Data Mining and Real Application Testing optionsHere is a sample of my test code:
# Define Plsql Anonymous Block
$Table1 = 'AdvSearch_Statutes'
$Table2 = ($Table1).Substring(0, $Table1.Length-1) + '_Docs'
$Caml_Doc_Id = 'CHP201500010'
$Sql = " DECLARE "
$Sql += " vCamlId VARCHAR2(30) := ':Param1' "
$Sql += " vPath_Tx VARCHAR2(200); "
$Sql += " vDelRows_Nr PLS_INTEGER := 0; "
$Sql += " CURSOR Docs_Cur IS "
$Sql += " SELECT XPath "
$Sql += " FROM $Table2 "
$Sql += " WHERE Caml_Doc_Id = vCamlId; "
$Sql += " BEGIN "
$Sql += " OPEN Docs_Cur; "
$Sql += " LOOP "
$Sql += " FETCH Docs_Cur INTO vPath_Tx; "
$Sql += " EXIT WHEN Docs_Cur%NOTFOUND; "
$Sql += " IF (DBMS_XDB.ExistsResource(vPath_Tx)) "
$Sql += " THEN "
$Sql += " DelRows_Nr := DelRows_Nr + 1; "
$Sql += " DBMS_XDB.DeleteResource(vPath_Tx, DBMS_XDB.DELETE_RECURSIVE_FORCE); "
$Sql += " END IF; "
$Sql += " END LOOP; "
$Sql += " DELETE FROM $Table2 WHERE Caml_Doc_Id = vCamlId; "
$Sql += " vDelRows_Nr := vDelRows_Nr + SQL%ROWCOUNT; "
$Sql += " DELETE FROM $Table1 WHERE Caml_Doc_Id = vCamlId; "
$Sql += " vDelRows_Nr := vDelRows_Nr + SQL%ROWCOUNT; "
$Sql += " SELECT vDelRows_Nr INTO :Param2 FROM Dual; "
$Sql += " EXCEPTION "
$Sql += " WHEN OTHERS THEN ROLLBACK; "
$Sql += " END; "
# Set up the Connection and command objects using the prior defined information. Ensure that
# Bind by name is used.
$Conn = New-Object Oracle.DataAccess.Client.OracleConnection($Connect_Str)
$Cmd = New-Object Oracle.DataAccess.Client.OracleCommand($Sql, $Conn)
$Cmd.BindByName = $True
#Set up the parameters for use with the Sql command.
$Param1 = New-Object Oracle.DataAccess.Client.OracleParameter
$Param2 = New-Object Oracle.DataAccess.Client.OracleParameter
$Param1.DbType = 'AnsiString'
$Param1.OracleDbType = 'Varchar2'
$Param1.Direction = 'Input'
$Param1.ParameterName = ':Param1'
$Param1.Value = $Caml_Doc_Id
$Param2.DbType = 'Int32'
$Param2.OracleDbType = 'Int32'
$Param2.Direction = 'Output'
$Param2.ParameterName = ':Param2'
[Void] $Cmd.Parameters.Add($Param1)
[Void] $Cmd.Parameters.Add($Param2)
# Open connection to database and execute the command
Try
$Conn.Open();
$Result = $Cmd.ExecuteNonQuery();
If ($Param2.Value -Eq $Null) {$Counts = 0}
Else {$Count = ($Param2.Value).ToString()}
Write-Host "Return Code: $Result"
Write-Host "Rows Deleted: $Counts"
Catch [System.Exception]
$Param2
Write-Host $_.Exception.ToString() -ForeGroundColor "Red"
Finally
$Conn.Close();
$Conn.Dispose();
"`nSuccessful end of script"
}I have some output. It all seems to be okay. I am following a book rather closely, but after several attempts changing one thing or another, I still cannot find a way to send an out value. I have commented out the " SELECT vDelRows_Nr INTO :Param2 FROM Dual; " and that is the problem statement. Thank you for your help. The first portion is the plsql being echoed back, then I list out what Param2 is defined at. The last bit is the error returned.
PS L064217> .\Test_Odp_PLsqlBlock.ps1
DECLARE vCamlId VARCHAR2(30) := ':Param1' vPath_Tx VARCHAR2(200); vDelRows_Nr PLS_INTEGER := 0;
CURSOR Docs_Cur IS SELECT XPath FROM AdvSearch_Statute_Docs WHERE Caml_Doc_Id = vCamlId; BEGIN
OPEN Docs_Cur; LOOP FETCH Docs_Cur INTO vPath_Tx; EXIT WHEN Docs_Cur%NOTFOUND; IF (DBMS_XDB.ExistsR
esource(vPath_Tx)) THEN DelRows_Nr := DelRows_Nr + 1; DBMS_XDB.DeleteResource(vPath_Tx, DBMS_XDB.DEL
ETE_RECURSIVE_FORCE); END IF; END LOOP; DELETE FROM AdvSearch_Statute_Docs WHERE Caml_Doc_Id = vCamlId; v
DelRows_Nr := vDelRows_Nr + SQL%ROWCOUNT; DELETE FROM AdvSearch_Statutes WHERE Caml_Doc_Id = vCamlId; vDelRows_Nr
:= vDelRows_Nr + SQL%ROWCOUNT; SELECT vDelRows_Nr INTO :Param2 FROM Dual; EXCEPTION WHEN OTHERS THEN ROLLBACK;
END;
DbType : Int32
SourceColumnNullMapping : False
Direction : Output
IsNullable : False
Offset : 0
OracleDbTypeEx : Int32
OracleDbType : Int32
ParameterName : :Param2
Precision : 0
Scale : 0
Size : 0
ArrayBindSize :
SourceColumn :
SourceVersion : Current
Status : Success
ArrayBindStatus :
CollectionType : None
Value :
UdtTypeName :
Oracle.DataAccess.Client.OracleException ORA-01036: illegal variable name/number at Oracle.DataAccess.Client.OracleEx
ception.HandleErrorHelper(Int32 errCode, OracleConnection conn, IntPtr opsErrCtx, OpoSqlValCtx* pOpoSqlValCtx, Object sr
c, String procedure, Boolean bCheck)
at Oracle.DataAccess.Client.OracleCommand.ExecuteNonQuery()
at CallSite.Target(Closure , CallSite , Object )Edited by: CRoberts on Nov 28, 2012 7:30 PMAs test
use NUMBER instead of PLS_INTEGER in PL/SQL
and
use Decimal instead of Int32 for Oracle parameter datatype -
Oracle SQL Developer 3.0: PL/SQL debugging of anonymous blocks: ISSUES
Hello,
I just downloaded the Oracle SQL Developer 3.0. I have been using the EA releases as they came into existence and was happy to see the released version. So I immediately tried to debug an anonymous block (something I did not try to do in the EA releases), and nothing happened.
The "Debug" was grayed out and the key-chord "ctrl-shift-F10" did nothing. I found this forum:
Re: 30EA1: anonymous block debugging?
and followed Vadim Tropashko's advice. This did nothing for my anon. block but worked fine for the simple example.
So I started to whittle my anon. block down to find the culprit, here is a repeatable breaking point for me:
declare
stmt1 long;
stmt2 long;
stmt3 long;
stmt4 long;
p_data varchar2( 500 );
i varchar2( 10 );
BEGIN
STMT1 := 1;
STMT2 := 1;
STMT3 := 1;
STMT4 := 1;
--the moment this is in the block "Debug" is no longer an option
select
SendDocumentResult
into
p_data
from
XMLTABLE( '/data'
PASSING
xmltype.createxml( '<?xml version="1.0" encoding="utf-8"?><data><SendDocumentResult>test</SendDocumentResult></data>' )
COLUMNS SendDocumentResult varchar2( 1000 ) PATH 'SendDocumentResult' ) ;
end;The moment I have the SELECT INTO ... XMLTABLE() it fails (a normal SELECT INTO works just fine).
Is this a problem with my environment or is a problem with SQL Developer 3.0.04. Looking over K's comments, it seems the debug worked for 'simple' blocks, so I wonder if this is just out-of-scope...
My environment:
Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - 64bit Production
PL/SQL Release 11.2.0.1.0 - Production
CORE 11.2.0.1.0 Production
TNS for IBM/AIX RISC System/6000: Version 11.2.0.1.0 - Production
NLSRTL Version 11.2.0.1.0 - Production
and Oracle SQL Developer
3.0.04 (Buld Main 04.34 with bundled Java) on a Window's XP box.Thanks, I'll survive. Just my luck, the first item I try to anon. debug didn't work! :)
thanks, hopefully this problem will be few and far between -
Calling PL/SQL anonymous block from href in tabular report
apex 2.2.
I've got a tabular report where I've added some img columns with a href to call diff processes
for example
"<a href="f?p=&APP_ID.:22:&APP_SESSION.:BRANCH_TO_PAGE_ACCEPT|NEW_PROXY:NO:::22,ABCDEF ><img src="/i/asyl.gif" border="0" alt="Runprocess"></a>"
When clicking on an image column in row x then I would like to run the process - no page submit.
The pl/sql anonymous block process source calls package.storedproc(p1,p2) - two in parameters
I'm struggling with the syntax and is wondering if there's a smarter way to achieve the same function
Any ideas most welcome
Thanks
Peter<a href="f?p=&APP_ID.:22:&APP_SESSION.:BRANCH_TO_PAGE_ACCEPT|NEW_PROXY:NO:::22,ABCDEFG" ><img src="/i/asylogin.gif" border="0" alt="Process"></a>Question is how can you pass values from a row in a tabular report to the application process ?
-
Anonymous Block with Variable and SELECT
Hi Guys,
I am struggling to connect the material I am learning. I read about anonymous blocks and variables so I want to write a
nice and neat select with all the fancy stuff (variables, exceptions) to get it right and to it as I read in the book.
DECLARE
MYSTRING VARCHAR(10);
MYSTIRNG := 'X';
BEGIN
SELECT * FROM DUAL WHERE DUMMY = MYSTRING
END;
but....this causes one error after the other. Am I getting the concept wrong here or is it a syntax error?cant I just get the result without using variable to store the result in the first place???Perhaps you're better off using a REF CURSOR (a.k.a. cursor variable).
That way you'll pass a resultset to the caller and you don't need any variables to select into.
You can read about them here:
http://www.oracle-base.com/articles/misc/UsingRefCursorsToReturnRecordsets.php
Re: PL/SQL 101 : Understanding Ref Cursors
http://download.oracle.com/docs/cd/E11882_01/appdev.112/e10766/tdddg_subprograms.htm#TDDDG99939 -
Need to execute a anonymous block
Hi guys,
I have one proc like below.
proc_expl(
empid in number,
ename in varchar2,
marks in marks_typ);
marks_type is record type which consists of 3 subjects.
marks_typ(sub1 number, sub2 number, sub3 number)
and i declared with table type this record type.
now I want to execute anonymous block and i am giving parameter values like below:
declare
empid in number,
ename in varchar2,
marks in marks_typ
begin
empid := 123,
ename := 'abc',
marks marks_typ := marks_typ(55,67,78);
proc_expl(
empid => empid,
ename => ename,
marks => marks_typ);
end;
can any one please suggest me why this is not executing properly.
thanks in advance!
Rgds,
LKRTry the below
CREATE OR REPLACE TYPE marks_type IS OBJECT (sub1 NUMBER(10),
sub2 NUMBER(10),
sub3 NUMBER(10)
CREATE OR REPLACE TYPE marks_typ IS TABLE OF marks_type;
CREATE OR REPLACE PROCEDURE proc_expl(empid NUMBER,
ename VARCHAR2,
marks marks_typ
AS
v_marks marks_typ:= marks;
BEGIN
FOR i IN 1..v_marks.COUNT
LOOP
DBMS_OUTPUT.PUT_LINE(v_marks(i).sub1||','||v_marks(i).sub2||','||v_marks(i).sub3);
END LOOP;
END;
SET SERVEROUTPUT ON
DECLARE
empid NUMBER;
ename VARCHAR2(20);
marks marks_typ := marks_typ();
BEGIN
empid := 123;
ename := 'abc';
marks.extend;
marks(1) := marks_type(55,67,78);
proc_expl(empid,ename,marks);
END;
Execution:-
SQL> DECLARE
2 empid NUMBER;
3 ename VARCHAR2(20);
4 marks marks_typ := marks_typ();
5 BEGIN
6 empid := 123;
7 ename := 'abc';
8 marks.extend;
9 marks(1) := marks_type(55,67,78);
10 proc_expl(empid,ename,marks);
11 END;
12 /
55,67,78
PL/SQL procedure successfully completed.
Hope it helps -
PL/SQL Anonymous Block - Trying to Call Function within Cursor
Hello -
I need to create an anonymous block that contains a cursor and a function. I want to call the function from within the cursor, and the function will basically take an ID as its IN parameter, and will return a comma separated list of values.
However, when I try to do this I get the error " function 'GET_PAYMENT_DATES' may not be used in SQL".
Does anyone know of a workaround? I'm trying to avoid having to store this function.
Thanks,
ChristineExploring Keith's suggestion of using the function code inline in your SQL:
test@ORA10G>
test@ORA10G> --
test@ORA10G> drop table t;
Table dropped.
test@ORA10G> drop table monetary_trans;
Table dropped.
test@ORA10G>
test@ORA10G> create table monetary_trans as
2 select 1 household_id, trunc(sysdate)-10 received_date from dual union all
3 select 1, trunc(sysdate)-9 from dual union all
4 select 1, trunc(sysdate)-8 from dual union all
5 select 2, trunc(sysdate)-7 from dual union all
6 select 2, trunc(sysdate)-6 from dual;
Table created.
test@ORA10G>
test@ORA10G> create table t as
2 select rownum x, rownum*10 y from dual connect by level <= 4;
Table created.
test@ORA10G>
test@ORA10G> --
test@ORA10G> select * from monetary_trans;
HOUSEHOLD_ID RECEIVED_
1 28-DEC-08
1 29-DEC-08
1 30-DEC-08
2 31-DEC-08
2 01-JAN-09
test@ORA10G> select * from t;
X Y
1 10
2 20
3 30
4 40
test@ORA10G>
test@ORA10G> --
test@ORA10G> -- the function code could be rewritten as follows
test@ORA10G> --
test@ORA10G> select household_id,
2 ltrim(sys_connect_by_path(rd,','),',') payment_dates
3 from
4 (
5 select household_id,
6 to_char(received_date,'mm/dd/yy') as rd,
7 row_number() over (partition by household_id order by 1) rn,
8 count(*) over (partition by household_id) cnt
9 from monetary_trans
10 -- and the constraints here in the where clause
11 )
12 where level = cnt
13 start with rn = 1
14 connect by prior household_id = household_id
15 and prior rn = rn - 1
16 and household_id = 1 -- <== this is the input parameter value
17 ;
HOUSEHOLD_ID PAYMENT_DATES
1 12/28/08,12/29/08,12/30/08
test@ORA10G>
test@ORA10G> --
test@ORA10G> -- and can be used as an inline view when joined with other tables
test@ORA10G> --
test@ORA10G> select t.y,
2 fn.payment_dates
3 from t,
4 (select household_id,
5 ltrim(sys_connect_by_path(rd,','),',') payment_dates
6 from (select household_id,
7 to_char(received_date,'mm/dd/yy') as rd,
8 row_number() over (partition by household_id order by 1) rn,
9 count(*) over (partition by household_id) cnt
10 from monetary_trans)
11 where level = cnt
12 start with rn = 1
13 connect by prior household_id = household_id
14 and prior rn = rn - 1
15 ) fn
16 where t.x = fn.household_id
17 ;
Y PAYMENT_DATES
10 12/28/08,12/29/08,12/30/08
20 12/31/08,01/01/09
test@ORA10G>
test@ORA10G>HTH
isotope -
Pass credentials to cmd in script block
Hi all so I'm invoking .cmd files to install software with cmd on remote machines using the invoke command in Powershell. It works fine for must software however when I try to install powershell on a remote machine it throws an exit code 5. I looked this
up and it is a credential error. Is there anyway for me to pass my credential in the script block but also to cmd?
Here is what I have now:
Invoke-Command -ComputerName $item -Credential $cred -ScriptBlock {cmd /c "C:\Package\install.cmd"} -AsJob
Thanks!What does your install.cmd actually do? Does it pull from another server or do anything related to a different remote system? If so, that will be denied by design as it is a 'double hop'. You would either need to enable CredSSP on that server or setup a
RunAsAccount on the remote endpoint to allow access to another remote system from your current system that has the endpoint.
cmd doesn't take credential objects and this shouldn't be an issue as you are passing your credentials to the scriptblock by default with the remote endpoint via the -Credential parameter. If you wanted to run cmd from another process under your provided
credentials, you would need to use Start-Process with the -Credential parameter, but again, this is only going to be useful if you wanted to supply alternate credentials beyond what you are providing with Invoke-Command.
Boe Prox
Blog |
Twitter
PoshWSUS |
PoshPAIG | PoshChat |
PoshEventUI
PowerShell Deep Dives Book
Maybe you are looking for
-
My iphone is not syncing with iCloud
Hi, i have just noticed (it may have been going on for a few weeks) that my iPhone 4 (IOS6) will not sync with icloud. This has not been a problem in the past. If I put a new event on the phone, it is not shown on icloud and vice-versa. Any ideas?
-
Templates saved as docs freezing Word
Hi, I hope someone can help. I have some word templates, that I open and then save as docs. I do this dozens of times every week but some of them (not all) cause a problem. I can see the file is saved as a doc, but when I try to open it, it says it i
-
How to declare a header line table in class
Hi Experts ; I m writing a class.I must display a picture in class. So Im find a below code TYPES: BEGIN OF ZW3QUERY, NAME(30) TYPE C, VALUE(255) TYPE C, END OF ZW3QUERY. data DOCKING type ref to CL_GUI_DOCKING_CONTAI
-
I had go pro footage in last import but when I imported next files it disappeared. Does not show up in last 12 months but deleted files from initial import are in the trash. Any suggestions?
-
What's difference on Oracle SOA Architect ,IBM SOA architect and Erl's Soa
HI im new to oracle fusion middleware 11g, please anyone clearify what the nature of job for oracle soa architect and developer. Is it necessary to study oracle soa suite concept in order to attend the oracle soa architect certificate. I heard that m