Pass parameter to pl/sql block
Hi,
I am getting following error when trying to create staging table from shell script by passing parameter.
SQL*Loader-941: Error during describe of table T1_1DAY_STG
ORA-04043: object T1_1DAY_STG does not existThis is PL/SQL block being called inside shell script
begin
execute immediate 'create table t1_&1._stg as select * from t1_rpt_tmt';
end Shell Script Call
load_data_to_oracle()
for i in 1DAY 7DAY 15DAY
do
${ORACLE_HOME}/bin/sqlplus ${ORACLE_USER}/${ORACLE_PASSWD}@${ORACLE_SID} << EOF > ${TMP_LOG_FILE} 2>&1
set serveroutput on
@${CREATE_STAGE_SQL} "$i"
COMMIT;
QUIT;
EOF
########Main#######
load_data_to_oracleThanks
Sandy
It is probably a permission issue. Are you the owner of the table you are trying to select from in your PL/SQL block? if not, do you have select permission granted specifically?
Here is my test:
test > create table T_ABC (a number, b number);
Table created.
test > @t_abc Hello
test > begin
2
3 execute immediate 'create table t1_&1._stg as select * from t_abc';
4
5 end;
6 /
old 3: execute immediate 'create table t1_&1._stg as select * from t_abc';
new 3: execute immediate 'create table t1_Hello_stg as select * from t_abc';
PL/SQL procedure successfully completed.
test > desc t1_Hello_stg
Name
A
B
test > desc T_ABC
Name
A
B
test >
Similar Messages
-
How to pass parameter to pl/sql block
Hi,
I am getting following error when trying to create staging table from shell script by passing parameter.
SQL*Loader-941: Error during describe of table T1_1DAY_STG
ORA-04043: object T1_1DAY_STG does not existThis is PL/SQL block being called inside shell script
begin
execute immediate 'create table t1_&1._stg as select * from t1_rpt_tmt';
endShell Script Call
load_data_to_oracle()
for i in 1DAY 7DAY 15DAY
do
${ORACLE_HOME}/bin/sqlplus ${ORACLE_USER}/${ORACLE_PASSWD}@${ORACLE_SID} << EOF > ${TMP_LOG_FILE} 2>&1
set serveroutput on
@${CREATE_STAGE_SQL} "$i"
COMMIT;
QUIT;
EOF
########Main#######
load_data_to_oraclethanks
sandyi dont understand why you want run it from shell script. you can write procedure like this :
SQL>
SQL> CREATE OR REPLACE PROCEDURE mytestProc(p_in VARCHAR2) AS
2 begin
3 FOR i IN (select REGEXP_SUBSTR(p_in,'[^,]+',1,ROWNUM) tblName
4 from dual
5 CONNECT BY INSTR(p_in, ',', 1, level - 1) > 0)
6 LOOP
7 execute immediate 'create table t1_'||i.tblname||'_stg as select * from myt2';
8 END LOOP;
9 end;
10 /
Procedure createdand run it
SQL> exec mytestProc('1day,7day,15day');
PL/SQL procedure successfully completed
SQL> select * from t1_15day_stg
2 union all
3 select * from t1_1day_stg
4 union all
5 select * from t1_7day_stg;
T N
SQL>
SQL> drop table t1_15day_stg;
Table dropped
SQL> drop table t1_1day_stg;
Table dropped
SQL> drop table t1_7day_stg;
Table dropped
SQL> purge table t1_15day_stg;
Done
SQL> purge table t1_1day_stg;
Done
SQL> purge table t1_7day_stg;
Done
SQL> -
Can we pass objects to pl/sql block
hi,
can we pass objects to pl/sql block.i think we can.how to pass it.help me in getting the examples of "passing objects to pl/sql block"What exactly do you mean ? You can pass objects like any other parameters
into and out from procedures/functions:
SQL> create or replace procedure get_object(myobj in out nocopy my_obj)
2 is
3 begin
4 dbms_output.put_line('ID : ' || myobj.empno);
5 dbms_output.put_line('Salary : ' || myobj.sal);
6 dbms_output.put_line('Department : ' || myobj.deptno);
7 myobj.sal := myobj.sal*2;
8 end;
9 /
Procedure created.
SQL> declare
2 mo my_obj := my_obj(1,1000,10);
3 begin
4 get_object(mo);
5 dbms_output.put_line('New salary : ' || mo.sal);
6 end;
7 /
ID : 1
Salary : 1000
Department : 10
New salary : 2000
PL/SQL procedure successfully completed.Rgds. -
Can i pass output from PL/SQL Block (Urgent)
Dear All,
I am calling ABC.sql from Shell Script using input parameters.
eg.
Declare
X varchar(12) := &1;
Begin
Select..........................
Exception
End;
This &1 parameter i am passing from shell script.
Like that, is it possible to pass output parameter to Shell script.
Thanks,
VikasI don't usually do Windows but ...
C:\TEMP>type t.bat
@@echo off
for /f %%D in ('sqlplus -s user/password@instance @t.sql 1') do (
set res=%%D)
echo result is %res%
C:\TEMP>type t.sql
var x VARCHAR2(10);
set pages 0 feedback off echo off verify off;
BEGIN
SELECT 'Hello' INTO :x
FROM dual
WHERE 1 = &1;
END;
print x;
exit;
C:\TEMP>t.bat
result is Hellosprings to mind as one way to do it.
Amiel:
Yes, you can use the sqlplus exit command to return a value but there are couple of limitations. The return value must be a number (enforced by sqlplus), and it must be less than 256, and on some operating systems less than 128.
John -
Passing parameter to a SQL query - Please help
Hi All,
I am new to JDBC. I have been trying to pass an external variable to an SQL Query.
The query is
String username1="le";
PreparedStatement pstmt = null;
pstmt = c.prepareStatement("select * from users where USER_NAME like '%?%'");
pstmt.setString(1, username1);
pstmt.executeQuery();
ResultSet rs = pstmt.getResultSet();
I am trying to retrieve values from the users table where the USER_NAME column value that is a String contains the supplied value username1.
I am using the question mark (?) character to pass the value from the variable username1. I am also using the '%' substitution character which matches for any number of characters. So, the above query should retrieve rows where the USER_NAME is something like "charles","leander","Elena" etc.( that contains "le")
I am getting the error:
SQLException: java.sql.SQLException: ORA-01006: bind variable does not exist
I changed the query to
PreparedStatement pstmt = null;
pstmt = c.prepareStatement("select * from users where USER_NAME like '% " + username1 + "%'");
//pstmt.setString(1, username1);
pstmt.executeQuery();
This time , it is not giving the error and retrieving properly.
But I want to use the original query and use the "pstmt.setString(1, username1); " . Is there any way of achieving this?
Please help.
Cheers,
charles_amhi,
try this...
String username1="%le%";
pstmt = c.prepareStatement("select * from users where USER_NAME like ?")
pstmt.setString(1,username1);
cheers,
rpk -
Passing parameter to Report SQL through Dialog box
I want to modify my reprt designer, so that while running, it ask me to insert a date. On inserting date in the dialog box, the report should be generated for the corresponding date. In case of no_data, it should show error. Please help me.
Yes, except you need to add &department=10 to the end of the page URL, not what I had.
Look at
How to pass values from a Page to portlet in Portal.
http://metalink.oracle.com/metalink/plsql/ml2_documents.showDocument?p_database_id=FOR&p_id=335031.996
for a complete description on how to setup page parameters and associate them with bind variables. -
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; -
I am having trouble with passing dynamic string to sql query for executing SSRS reports.
I am using oracle database and I want to pass where clause parameter as "where LAND_NR = 6" to my select query.
For example: I want to execute Select * from employee :p_where.
where p_where parameter holds value "where LAND_NR = 6"
So it will treat as "Select * from employee where LAND_NR = 6" statement which will give me the list of records to display in my reports.
But it's not taking correct sql command throwing an error as "SQLcommand not properly ended."
How can I achieve this?You need to use dynamic sql
But please keep in mind that since you're using Oracle you may be better off posting this in some Oracle forums
This forum is specifically for SQL Server
Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs -
How do I Pass a parameter to a SQL Component Task where the source SQL statement is also a variable
Hi,
I have been tasked with making a complex package more generic.
To achieve this I need to pass a parameter to a SQL Component Task where the source SQL statement is also a variable.
So to help articulate my question further I have create a package and database as follows; -
USE [KWPlay]
GO
/****** Object: Table [dbo].[tblTest] Script Date: 05/14/2014 17:08:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tblTest](
[ID] [bigint] IDENTITY(1,1) NOT NULL,
[Description] [nvarchar](50) NULL,
CONSTRAINT [PK_tblTest] PRIMARY KEY CLUSTERED
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
I populated this table with a single record.
I unit tested the SQL within SSMS as follows;
SELECT * FROM dbo.tblTest
Result; -
ID
Description
1
Happy
DECLARE @myParam NVARCHAR(100)
SET @myParam = 'Sad'
UPDATE dbo.tblTest SET [Description] = @myParam FROM dbo.tblTest WHERE ID = 1
SELECT * FROM dbo.tblTest
Result; -
ID
Description
1
Sad
Within the package I created two variables as follows; -
Name: strSQL
Scope: Package
Data Type: String
Value: UPDATE dbo.tblTest SET [Description] = @myParam FROM dbo.tblTest WHERE ID = 1
Name: strStatus
Scope: Package
Data Type: String
Value: Happy
I then created a single ‘Execute SQL Task’ component within the control flow as follows; -
However when I run the above package I get the following error; -
SSIS package "Package.dtsx" starting.
Error: 0xC002F210 at Execute SQL Task, Execute SQL Task: Executing the query "UPDATE dbo.tblTest SET [Description] = @myParam FR..." failed with the following error:
"Parameter name is unrecognized.". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly.
Task failed: Execute SQL Task
Warning: 0x80019002 at Package: SSIS Warning Code DTS_W_MAXIMUMERRORCOUNTREACHED.
The Execution method succeeded, but the number of errors raised (1) reached the maximum allowed (1); resulting in failure. This occurs when the number of errors reaches the number specified in MaximumErrorCount. Change the MaximumErrorCount or fix the
errors.
SSIS package "Package.dtsx" finished: Failure.
I also tried; -
Name: strSQL
Scope: Package
Data Type: String
Value: UPDATE dbo.tblTest SET [Description] = ? FROM dbo.tblTest WHERE ID = 1
However I received the error; -
SSIS package "Package.dtsx" starting.
Error: 0xC002F210 at Execute SQL Task, Execute SQL Task: Executing the query "UPDATE dbo.tblTest SET [Description] = ? FROM dbo...." failed with the following error: "Parameter name is unrecognized.". Possible failure reasons: Problems with
the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly.
Task failed: Execute SQL Task
Warning: 0x80019002 at Package: SSIS Warning Code DTS_W_MAXIMUMERRORCOUNTREACHED. The Execution method succeeded, but the number of errors raised (1) reached the maximum allowed (1); resulting in failure. This occurs when the number of errors reaches
the number specified in MaximumErrorCount. Change the MaximumErrorCount or fix the errors.
SSIS package "Package.dtsx" finished: Failure.
Kind Regards,
Kieran.
Kieran Patrick Wood http://www.innovativebusinessintelligence.com http://uk.linkedin.com/in/kieranpatrickwood http://kieranwood.wordpress.com/Tried; -
Name: strSQL
Scope: Package
Data Type: String
Value: UPDATE dbo.tblTest SET [Description] = ? FROM dbo.tblTest WHERE ID = 1
and; -
Result; -
SSIS package "Package.dtsx" starting.
SSIS package "Package.dtsx" finished: Success.
Therefore the answer was to put the parameter number rather than the parameter name under the parameter mapping tab-> parameter name column.
Kieran Patrick Wood http://www.innovativebusinessintelligence.com http://uk.linkedin.com/in/kieranpatrickwood http://kieranwood.wordpress.com/ -
PL/SQL block query error when going to a remote system with 1 parameter.
Hi,
I am getting the error:
Invalid function body condition: ORA-01460: unimplemented or unreasonable conversion requested ORA-02063: preceding line from HANSEN_REMOTE
The issue appears to result from opening a cursor that is a select statement is in some way accessing records via a dblink and the 'where' clause is has more then one session parameter in it. Here is the smallest pl/sql block that results with an error:
DECLARE
CURSOR c_GetPay IS
SELECT PERSON_ID
FROM CASH_PERSON@HANSEN_REMOTE
WHERE LAST_NAME = :P320_HANSEN_LAST_NAME
AND FIRST_NAME = :P320_HANSEN_FIRST_NAME;
BEGIN
OPEN c_GetPay ;
CLOSE c_GetPay ;
RETURN TRUE;
END ;
If I remove 'AND FIRST_NAME = :P320_HANSEN_FIRST_NAME' from the curser, there is no problem. This block of pl/sql is in a On Load: Before Header
on a page branch. This issue remains consistent in our 1.6.1.00.02 instance of HTMLDB with an Oracle database version 10.1.0.3.0. This instance is
a fresh install of the 10g and HTMLDB.
Does any one have any ideas of why I am getting this error message. I really need to get it resolve soon as we are trying to get an application up by the end of August and there is still alot of coding needing to be done.
Thanks for the help.
LanieScott, I have tried everything that this point except copy the whole table from the remote system.
Here is a short version of what I have tried...
-- hard coded condition...timing was not an issue here...it was quick.
declare
v_in_PersonId number(9);
cursor c_GetPay
IS select PERSON_ID --, first_name, LAST_NAME
from HANSEN_CONTACT
where first_name like 'LANIE'
AND last_name LIKE 'MOORE'
BEGIN
OPEN c_GetPay;
FETCH c_GetPay INTO v_in_PersonId;
CLOSE c_GetPay;
RETURN TRUE;
END
-- this is an internal variable set to the string literal...does not as the v function was not called.
declare
V_TEST VARCHAR2(150);
V_TEST2 VARCHAR2(150);
v_in_PersonId number(9);
cursor c_GetPay
IS select PERSON_ID --, first_name, LAST_NAME
from HANSEN_CONTACT
where first_name like :V_TEST
AND last_name LIKE :V_TEST2
BEGIN
V_TEST := 'LANIE';
V_TEST2 := 'MOORE';
OPEN c_GetPay;
FETCH c_GetPay INTO v_in_PersonId;
CLOSE c_GetPay;
RETURN TRUE;
END
-- this has the v function called in the cursor since no matter what I do, I have to call it so I don't get my original error. This takes over a minute to return, and it is using hard coded values...if I use session variables where I place the information from the user, it takes even longer.
declare
V_TEST VARCHAR2(150);
V_TEST2 VARCHAR2(150);
v_in_PersonId number(9);
cursor c_GetPay
IS select PERSON_ID --, first_name, LAST_NAME
from HANSEN_CONTACT
where first_name like V(:V_TEST)
AND last_name LIKE V(:V_TEST2)
BEGIN
V_TEST := 'LANIE';
V_TEST2 := 'MOORE';
OPEN c_GetPay;
FETCH c_GetPay INTO v_in_PersonId;
CLOSE c_GetPay;
RETURN TRUE;
END
It does not appear to be an issue if I am looking at a view going to the remote system or the table it's self. The slowness issue takes place. (In short I have tried replacing HANSEN_CONTACT which is a view with the direct table link of imsv7.contact@HANSEN_REMOTE and that did not solve the timing issue).
Any ideas? -
Why named parameter can't be used multiple times in PL/SQL block in JDBC
with the following PL/SQL block, when I run int in JDBC, I get an error,
it says, The number of parameter names does not match the number of registered parameters.
if all named parameters are used only once, then my program works fine.
My old program uses Oracle Forms to run the attached PL/SQL block correctly, I just want to run them in JDBC without more efforts, I don't want to rewrite all PL/SQL blocks.
Does oracle driver support this case? why the PL/SQL block can work in Oracle Forms but failed in JDBC?
Can we have an another solutions to avoid rewriting the PL/SQL block to stored procedure?
if I use following SQL:
BEGIN if :q is null then :q := 'X'; else :q := 'Y'; end if; END;
, Using java program:
import java.sql.*; public class RunPLSQLBlock { public static void main(String s[]) throws SQLException { String URL = "jdbc:oracle:thin:@192.168.11.199:1521:TIBSTEST"; Connection con = null; try { Class.forName("oracle.jdbc.driver.OracleDriver"); con = (Connection) DriverManager.getConnection(URL, "FBP1DEV", "FBP1DEV"); String SQL = "BEGIN if :q is null then :q := 'X'; else :q := 'Y'; end if; END;"; CallableStatement stmt = con.prepareCall(SQL); stmt.registerOutParameter("q", Types.VARCHAR); stmt.setString("q", "A"); stmt.execute(); } catch (Exception e) { e.printStackTrace(); } finally { if (con != null) { con.close(); } } } }
in the coding, only "q" registered, I got:
java.sql.SQLException: The number of parameter names does not match the number of registered praremeters at oracle.jdbc.driver.OracleSql.setNamedParameters(OracleSql.java:314) at oracle.jdbc.driver.OracleCallableStatement.execute(OracleCallableStatement.java:10096) at oracle.jdbc.driver.OraclePreparedStatementWrapper.execute(OraclePreparedStatementWrapper.java:5693) at RunPLSQLBlock.main(RunPLSQLBlock.java:28)
now, tried to register 3 indexes, changed fragments are below.
import java.sql.*; public class RunPLSQLBlock { public static void main(String s[]) throws SQLException { String URL = "jdbc:oracle:thin:@192.168.11.199:1521:TIBSTEST"; Connection con = null; try { Class.forName("oracle.jdbc.driver.OracleDriver"); con = (Connection) DriverManager.getConnection(URL, "FBP1DEV", "FBP1DEV"); String SQL = "BEGIN if :q is null then :q := 'X'; else :q := 'Y'; end if; END;"; CallableStatement stmt = con.prepareCall(SQL); stmt.registerOutParameter(1, Types.VARCHAR); stmt.registerOutParameter(2, Types.VARCHAR); stmt.registerOutParameter(3, Types.VARCHAR); stmt.setString(1, "A"); stmt.execute(); } catch (Exception e) { e.printStackTrace(); } finally { if (con != null) { con.close(); } } } }
now error changed to:
java.sql.SQLException: ORA-01006: bind variable does not exist at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:457) at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:400) at oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:926) at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:476) at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:200) at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:543) at oracle.jdbc.driver.T4CCallableStatement.doOall8(T4CCallableStatement.java:208) at oracle.jdbc.driver.T4CCallableStatement.executeForRows(T4CCallableStatement.java:1416) at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1757) at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:4372) at oracle.jdbc.driver.OraclePreparedStatement.execute(OraclePreparedStatement.java:4595) at oracle.jdbc.driver.OracleCallableStatement.execute(OracleCallableStatement.java:10100) at oracle.jdbc.driver.OraclePreparedStatementWrapper.execute(OraclePreparedStatementWrapper.java:5693) at RunPLSQLBlock.main(RunPLSQLBlock.java:26)
, now tried register only 1 position like below,
CallableStatement stmt = con.prepareCall(SQL); stmt.registerOutParameter(1, Types.VARCHAR); stmt.setString(1, "A"); stmt.execute();
, it says:
java.sql.SQLException: Missing IN or OUT parameter at index:: 2 at oracle.jdbc.driver.OraclePreparedStatement.processCompletedBindRow(OraclePreparedStatement.java:2177) at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:4356) at oracle.jdbc.driver.OraclePreparedStatement.execute(OraclePreparedStatement.java:4595) at oracle.jdbc.driver.OracleCallableStatement.execute(OracleCallableStatement.java:10100) at oracle.jdbc.driver.OraclePreparedStatementWrapper.execute(OraclePreparedStatementWrapper.java:5693) at RunPLSQLBlock.main(RunPLSQLBlock.java:26)
, now let try a OK case, which use all named parameters only once. coding like below, SQL and Java listed below.
BEGIN if :q is null then :r := 'X'; else :s := 'Y'; end if; EXCEPTION WHEN NO_DATA_FOUND THEN NULL; END;
import java.sql.*; public class RunPLSQLBlock { public static void main(String s[]) throws SQLException { String URL = "jdbc:oracle:thin:@192.168.11.199:1521:TIBSTEST"; Connection con = null; try { Class.forName("oracle.jdbc.driver.OracleDriver"); con = (Connection) DriverManager.getConnection(URL, "FBP1DEV", "FBP1DEV"); String SQL = "BEGIN if :q is null then :r := 'X'; else :s := 'Y'; end if; END;"; CallableStatement stmt = con.prepareCall(SQL); stmt.registerOutParameter("q", Types.VARCHAR); stmt.registerOutParameter("r", Types.VARCHAR); stmt.registerOutParameter("s", Types.VARCHAR); stmt.setString("q", "A"); stmt.execute(); System.out.println("Q :" + stmt.getString("q")); System.out.println("R :" + stmt.getString("r")); System.out.println("S :" + stmt.getString("s")); } catch (Exception e) { e.printStackTrace(); } finally { if (con != null) { con.close(); } } } }
, the case give us the following output:
Q :A R :null S :Y
2nd part, I also tried another scheme, to use 'execute immediate', test code attached below, it also have errors.
begin execute immediate 'begin if :q is null then :q := ''X''; else :q := ''Y''; :r := ''Z''; end if; end;' using in out :q, out :r; end;
, Java Code:
import java.sql.*; public class RunDynamicSQL { public static void main(String s[]) throws SQLException { String URL = "jdbc:oracle:thin:@192.168.11.199:1521:TIBSTEST"; Connection con = null; try { Class.forName("oracle.jdbc.driver.OracleDriver"); con = (Connection) DriverManager.getConnection(URL, "FBP1DEV", "FBP1DEV"); String SQL ="begin execute immediate 'begin if :q is null then :q := ''X''; else :q := ''Y''; :r := ''Z''; end if; end;' using in out :q, out :r; end;"; CallableStatement stmt = con.prepareCall(SQL); stmt.registerOutParameter("q", Types.VARCHAR); stmt.registerOutParameter("r", Types.VARCHAR); stmt.setString("q", "A"); stmt.execute(); System.out.println("Q :" + stmt.getString("q")); System.out.println("R :" + stmt.getString("r")); } catch (Exception e) { e.printStackTrace(); } finally { if (con != null) { con.close(); } } } }
, the output is, we can find when parameter 'q' is IN OUT mode, we can't get its final value:
Q :null R :Z
, now I tried my workaround, it works fine by using a temporary variable, now my named parameter is split to 2 roles, one is for IN, another is for OUT, now I can get final out value.
declare q clob; r clob; begin q := ?; r := ?; execute immediate 'begin if :q is null then :q := ''X''; else :q := ''Y''; :r := ''Z''; end if; end;' using in out q, out r; ? := q; ? := r; end;
, my test java code,
import java.sql.*; public class RunDynamicSQL { public static void main(String s[]) throws SQLException { String URL = "jdbc:oracle:thin:@192.168.11.199:1521:TIBSTEST"; Connection con = null; try { Class.forName("oracle.jdbc.driver.OracleDriver"); con = (Connection) DriverManager.getConnection(URL, "FBP1DEV", "FBP1DEV"); String SQL ="declare q clob;r clob; begin q := ?; r := ?; execute immediate 'begin if :q is null then :q := ''X''; else :q := ''Y''; :r := ''Z''; end if; end;' using in out q, out r; ? := q; ? := r; end;"; CallableStatement stmt = con.prepareCall(SQL); stmt.registerOutParameter(3, Types.VARCHAR); stmt.registerOutParameter(4, Types.VARCHAR); stmt.setString(1, "A"); stmt.setString(2, "A"); stmt.execute(); System.out.println("Q :" + stmt.getString(3)); System.out.println("R :" + stmt.getString(4)); } catch (Exception e) { e.printStackTrace(); } finally { if (con != null) { con.close(); } } } }
, the output is expected,
Q :Y R :Z
Database:
Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 - 64bit Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options
JDBC Driver, extracted from ojdbc6_g.jar/META-INF/MANIFEST.MF :
Created-By: 1.5.0_30-b03 (Sun Microsystems Inc.)
Implementation-Vendor: Oracle Corporation
Implementation-Title: JDBC debug
Implementation-Version: 11.2.0.3.0
Repository-Id: JAVAVM_11.2.0.3.0_LINUX_110823
Specification-Vendor: Sun Microsystems Inc.
Specification-Title: JDBC
Specification-Version: 4.0
Main-Class: oracle.jdbc.OracleDriver
JDK:
java version "1.7.0"
Java(TM) SE Runtime Environment (build 1.7.0-b147)
Java HotSpot(TM) Client VM (build 21.0-b17, mixed mode, sharing)
Edited by: jamxval on 2013-3-22 2:01PM (UTC+08:00), Give full test java program and SQL, added environment/API level; Attached another problem.
Edited by: jamxval on 2013-3-26 17:57 (UTC +08), Adjust code styleHi, thanks for your response, now I see, the named parameter is for stored procedure only, for PL/SQL block we name it placeholder name.
After cast my java.sql.CallableStatement to oracle.jdbc.OracleCallableStatement, I can find setStringAtName,
now, I have only one question:I can't find corresponding methods for registerOutputParameter, how we fetch output value?
I tried to callableStatement.getString("q"); it reports errors, but there are no ordinal binding in my source code, does placeholder names doesn't support OUT mode?
Java:
CallableStatement stmt = con.prepareCall("BEGIN if :q is null then :r := 'X'; else :s := 'Y'; end if; END;");
oracle.jdbc.OracleCallableStatement call = (oracle.jdbc.OracleCallableStatement) stmt;
call.registerOutParameter("q", Types.VARCHAR);
call.registerOutParameter("r", Types.VARCHAR);
call.registerOutParameter("s", Types.VARCHAR);
call.setStringAtName("q", "A");
call.setStringAtName("r", "A");
call.setStringAtName("s", "A");
call.execute();
System.out.println("Q :" + call.getString("q"));
</Java>
<output>
java.sql.SQLException: 不允许的操作: Ordinal binding and Named binding cannot be combined!
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:146)
at oracle.jdbc.driver.OracleCallableStatement.getString(OracleCallableStatement.java:2834)
at RunPLSQLBlock.main(RunPLSQLBlock.java:33)
</output>by the way, in my below-mentioned SQL 'problematic', when my code uses 'execute immediate' and use placeholder names in IN OUT mode, we always get NULL value (i.e. ':q'), but we can get final value of ':r' when ':r' is OUT mode only; now I get a workaround attached in below-mentioned 'my workaround' block, which split the IN OUT roles to 2 parts, it can work now;
It seems that the difference between 'problematic' and 'my workaround' imply that there are something work unexpectedly when the driver process the placeholder names, because 'my workaround' and ':r in problematic case' make sure the 'execute immediate' returned output values correctly, unluckly driver layer can't get return values.
<SQL name = 'problematic'>
begin
execute immediate 'begin if :q is null then :q := ''X''; else :q := ''Y''; :r := ''Z''; end if; end;'
using in out :q, out :r;
end;
</SQL>
<SQL name='my workaround'>
declare
q clob;
r clob;
begin
q := ?;
r := ?;
execute immediate 'begin if :q is null then :q := ''X''; else :q := ''Y''; :r := ''Z''; end if; end;' using in out q, out r;
? := q;
? := r;
end;Edited by: EJP on 26/03/2013 14:14 -
Pass parameter to sql statement in query manager
Hai to all,
I want to pass the percentage as the parameter into the sql statemnet.i what to execute it in the query manager.
If i execute that statement then cann't found the tablename error is coming.
Other than the data in the table (general data) pass to the parameter in the sql at runtime.
for example:
select [%0] *100
how to pass 10 to that sql statement.
Please help me...
Regards,
Raji.Hi Ramya,
You can create a SP with parameters to accept and then execut this SP from SAP Business One Query Manager by passing the parameter (in your case 10). The result will be as desired.
Ex:
Create this Procedure in SQL Management Studio
create proc Test(@a as int)
as
begin
select (@a*100)
end
To Execute the Query use this Query and pass the desired values with parameters
execute Test 10
Regards,
Reno -
How to pass a parameter into execute sql task and later use it into dataflow task?
i am in a situation, where i have a logging table in which i have a primary key called ETL_log_ID which is an identity column and acts as a foreign key for various fact table and dimension tables which are populated using SSIS packages. Now i wanna use the
ETL_log_ID as a parameter in the execute sql task which populates the log table and pass the same value in the data flow task which populates the facts and dimension. Can you let me know how to pass the parameter in a step by step procedure.
Thanks,
Nikhil
Nikhil,
You can check the following :
http://www.programmersedge.com/post/2013/03/05/ssis-execute-sql-task-mapping-parameters-and-result-sets.aspx
http://stackoverflow.com/questions/7610491/how-to-pass-variable-as-a-parameter-in-execute-sql-task-ssis
Regarding the usage in Dataflow task, Can you elaborate on that a little?
Thanks,
Jay
<If the post was helpful mark as 'Helpful' and if the post answered your query, mark as 'Answered'> -
How to Passing parameter in SQL.For Example,Table name=&From_Clause.It will asking table name at runtime.How to assign table name based on user.
Hi,
796776 wrote:
It will returm error.what problem in this
Select * From Emp a,
(SELECT CASE
WHEN USER = :UserType
THEN 'scott.Dept'
ELSE 'scott.order'
END AS b
FROM dual)
Where a.DeptNo= b.DeptNo &WhereClauseIt's hard to guess, from an example like this with so many errors, exactly what you're trying to do.
Please post a description of the problem, including CREATE TABLE and INSERT statments for any tables you need (unless you can state the problem using commonly available tables, such as those in the data dictionary or the scott schema), a few values of a parameter (or examples of different user names, if USER acts like a parameter) and the results you want from the same data for each value.
For example
"In addition to the scott.dept table, I have a table called my_dept: CREATE TABLE my_dept ...
which has this data: INSERT INTO my_dept ...
I need a script such that, when user scott runs it, the results are ...
but when any other user runs it, the results are ..
As you can see, the difference is ..."
Table names must be explicitly given when a SQL statement is compiled. That's why I usggested a preliminary query; so by the time you compiled the main query, the table name would be known and could be passed in a substitution variable.
If you really want to do it in one query, you can do a UNION of two queries, one of which returns nothing because of the parameter. It's not very efficient.
Maybe you are looking for
-
Copy Group or Layer to *Below* the Selected layer
Hey everyone, So I have a bit of a workflow problem. It's not a huge deal but it's one of those things that really adds up over time. Whenever I'm designing mock ups for a page I usually work from the top down. In cases of let's say laying out items
-
Sap script - please use meaningfull subject titles....
Hi, My requirement is to print theree texts in theree different lines.So I declared the texts in SAP script with the command "/". Buut in spool I am getting all the three texts in one single line.Can anyone suggest how to get the texts in three diffe
-
Is there a fix for a 2 inch black line on my iPad
Is there a fix for a 2 inch black line on my ipad
-
How to make it so guest acsess gets forwarded to url of my choose first time they log
I've got a connectivity problem, maybe two issues in one. I'll be using my MacBook Pro Mac OS 10.6.8 with my WNDR3400v1 router and my Actiontec...
-
I cannot get <cfflush> to work on a CF8 server. I am doing a simple cfoutput, running a cfx sleep tag, and then outputing more text with a cfoutput. On my CF6.1 server (which is identical besides the version of CF), this works correctly. On the CF8 s