ORA-01036: illegal variable name/number while running PL SQL block from nodejs - sql

I have following pl/sql block:
DECLARE
user_name varchar(255);
custom_exception EXCEPTION;
PRAGMA exception_init( custom_exception, -20001);
BEGIN
SELECT name
INTO user_name
FROM data_table where ID = '1';
IF user_name = 'temp' THEN
RAISE custom_exception;
END IF;
END;
When I run it from Oracle SQL Developer, it works fine.
But I am getting ORA-01036: illegal variable name/number while running it from nodejs.
Call from Nodejs code:
var output = await connection.execute(fs.readFileSync('path_to_pl_sql_file', 'utf8'), {
message: {
dir: oracledb.BIND_OUT,
type: oracledb.STRING,
maxSize: 100
}
}, {
autoCommit: true
});
Can someone point out what going wrong here?

The error was not with the PL/SQL block.
I was passing in bind variables while executing the PL/SQL from nodejs and that bind variable was not present in the SQL.
Hence the error!

Related

Why is my script not building in HelpNDoc? Error: Unknown name

I am trying to write a script:
const
// Define the output file
OUTPUT_FILE = 'd:\topics.txt';
var
// Current topic ID
aTopicId: string;
// List of output
aList: TStringList;
begin
// Init list
aList := TStringList.Create;
aList.Add('Topic Caption | Help ID | Help Context | Meta Description');
try
// Get first topic
aTopicId := HndTopics.GetTopicFirst();
// Loop through all topics
while aTopicId <> '' do
begin
// Add the topic to the list
aList.Add(Format('%s | %s | %d | %s', [
HndTopics.GetTopicCaption(aTopicId),
HndTopics.GetTopicHelpId(aTopicId),
HndTopics.GetTopicHelpContext(aTopicId),
HndTopics.GetTopicDescription(aTopicId)
]));
// Get next topic
aTopicId := HndTopics.GetTopicNext(aTopicId);
end;
// Create the file
aList.SaveToFile(OUTPUT_FILE);
finally
aList.Free;
end;
end.
When I build it in HelpNDoc:
Why is it saying:
[Error] script(9, 3): Unknown name "aList"
The authors of HelpNDoc provided some clarification about this issue. Starting with HelpNDoc 7, you need to add the var keyword each time you change the type: Migrating scripts from V6 to V7.
So my variable declaration section needed to be changed to something like:
var
// Current topic ID
aTopicId: string;
var
// List of output
aList: TStringList;
This is a limitation of HelpNDoc's scripting engine.

Can't call a procedure with multiline SQL code .. what is the syntax?

I can't get a multiline SQL statement to work within a procedure/javascript without putting \ after each line.
This works:
CREATE or replace PROCEDURE PR_DELETEME()
RETURNS VARCHAR
LANGUAGE javascript
AS
$$
var rs = snowflake.execute( { sqlText:
'create or replace table deleteme as select sysdate() as my_date;'
} );
return 'Done.';
$$;
This fails:
CREATE or replace PROCEDURE PR_DELETEME()
RETURNS VARCHAR
LANGUAGE javascript
AS
$$
var rs = snowflake.execute( { sqlText:
'create or replace table deleteme as
select sysdate() as my_date;'
} );
return 'Done.';
$$;
call PR_DELETEME(); gives...
JavaScript compilation error: Uncaught SyntaxError: Invalid or unexpected token in PR_DELETEME at ' 'create or replace table deleteme as' position 6
I really don't want to have to put \ at the end of each line.
Use "backticks" not single quotes or double quotes. Below now works:
CREATE or replace PROCEDURE PR_DELETEME()
RETURNS VARCHAR
LANGUAGE javascript
AS
$$
var rs = snowflake.execute( { sqlText:
`create or replace table deleteme as
select sysdate() as sysd;`
} );
return 'Done.';
$$;

Spring Data Jpa call to Stored Procedure

I am trying to create a method that call Stored Procedure to do a very easy insert and a select,
I created a stored procedure on an Oracle database as below:
CREATE OR REPLACE PROCEDURE schema.insertNewTable(p_test IN VARCHAR2, p_out OUT VARCHAR2)
IS
BEGIN
INSERT INTO NEWTABLE("TEST") VALUES(p_test);
SELECT '1' INTO p_out FROM DUAL;
COMMIT;
END;
Then on an Entity:
#Procedure(procedureName = "insertNewTable", outputParameterName="p_out")
String insertNewTable(#Param("p_test") String p_test);
but everytime i call this method i get this:
2018-06-23 20:04:43,047|ORA-06550: row 1, colonna 7:
PLS-00306: wrong number or types of arguments in call to 'INSERTNEWTABLE'
ORA-06550: riga 1, column 7:
PL/SQL: Statement ignored
2018-06-23 20:04:43,100|org.springframework.dao.InvalidDataAccessResourceUsageException: Error calling CallableStatement.getMoreResults; SQL [insertNewTable]; nested exception is org.hibernate.exception.SQLGrammarException: Error calling CallableStatement.getMoreResults
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:261)
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:244)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:503)
After a couple of tries (and exceptions), I modified the Entity and the call to avoid "OUT" types and, in this way, I have no errors:
CREATE OR REPLACE PROCEDURE schema.insertNewTable(p_test IN VARCHAR2)
IS
BEGIN
INSERT INTO NEWTABLE("TEST") VALUES(p_test);
COMMIT;
END;
Then on an Entity:
#Procedure(procedureName = "insertNewTable")
void insertNewTable(#Param("p_test") String p_test);
How can i fix this to get a return value?
with Spring DATA
in your repository:
1) calling with native SQL :
#Query(value = "select Store-procedure-name(:param) from dual", nativeQuery = true)
BigDecimal method-name(#Param("param") Long param);
2)
#Procedure(procedureName = "store-procedure-name", outputParameterName = "output-param-of-store-procedure")
return-type-of-store-procedure method-name(input-params-of-store-procedure);
you can use NamedStoredProcedureQuery
#NamedStoredProcedureQuery(
name = "insertNewTable",
procedureName = "insertNewTable",
parameters = {
#StoredProcedureParameter(mode = ParameterMode.IN, type = String.class, name
= "p_test"),
#StoredProcedureParameter(mode = ParameterMode.OUT, type = String.class, name
= "p_out"),
)
}
)
method call:
StoredProcedureQuery query =
this.em.createNamedStoredProcedureQuery("insertNewTable");
query.setParameter("p_test", ""TEST"");
query.execute();
String out = query.getOutputParameterValue("p_out");

How to get cursor from Oracle using Groovy?

I'm using a Groovy script in Mule ESB to get output parameters from Oracle stored procedure (including cursor) and getting an exception.
Minimal example:
import groovy.sql.Sql
import oracle.jdbc.pool.OracleDataSource
import oracle.jdbc.driver.OracleTypes
def ds = new OracleDataSource()
// setting data source parameters here
def sql = new Sql(ds)
def data = []
sql.call("""declare
result_table sys_refcursor;
begin
open result_table for select 1 as a from dual;
insert into CURSOR_TEST (ID) values (1);
commit;
${Sql.resultSet OracleTypes.CURSOR} := result_table;
insert into CURSOR_TEST (ID) values (2);
commit;
end;
"""
){ table ->
throw new RuntimeException("Never getting this exception.")
table.eachRow {
data << it.toRowResult()
}
}
sql.close()
return data
Error:
Message : java.sql.SQLException: Closed Statement (javax.script.ScriptException)
Code : MULE_ERROR--2
--------------------------------------------------------------------------------
Exception stack is:
1. Closed Statement(SQL Code: 17009, SQL State: + 99999) (java.sql.SQLException)
oracle.jdbc.driver.SQLStateMapping:70 (null)
2. java.sql.SQLException: Closed Statement (javax.script.ScriptException)
org.codehaus.groovy.jsr223.GroovyScriptEngineImpl:323 (http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/script/ScriptException.html)
3. java.sql.SQLException: Closed Statement (javax.script.ScriptException)
(org.mule.api.transformer.TransformerException)
org.mule.module.scripting.transformer.ScriptTransformer:39 (http://www.mulesoft.org/docs/site/current3/apidocs/org/mule/api/transformer/TransformerException.html)
--------------------------------------------------------------------------------
Root Exception stack trace:
java.sql.SQLException: Closed Statement
at oracle.jdbc.driver.SQLStateMapping.newSQLException(SQLStateMapping.java:70)
at oracle.jdbc.driver.DatabaseError.newSQLException(DatabaseError.java:133)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:199)
+ 3 more (set debug level logging or '-Dmule.verbose.exceptions=true' for everything)
********************************************************************************
Select from CURSOR_TEST returns 1 and 2.
Oracle server version: Oracle Database 11g Enterprise Edition Release 11.2.0.3.0 - 64bit Production.
Mule version: 3.5.0.
I'm using jdbc\lib\ojdbc6.jar from oracle client version 11.1.0.7.0.
What am I doing wrong?
The following code can help you get variable of SYS_REFCURSOR from Oracle anonymous block.
We should focus on a few key details:
Class groovy.sql.Sql doesn't have corresponding OutParameter and we make it manually as CURSOR_PARAMETER and pass it to sql.call method
Consider that the block starts with {call DECLARE and ends with END } without semicolon after END. Otherwise we can get a poorly recognizable SQLException in the face.
The question marks ? inside the sqlString are places for parameter bindings. Bindings are made in the natural order. In this example:
the first ? binds with the first element in parametersList: "abc", treating the value as IN parameter ;
the second ? binds with CURSOR_PARAMETER treating the value as OUT parameter of passed type;
There is only one enter into closure after sql.call and ResultSet rs provide rows of cursor my_cur declared in anonymous block.
import groovy.sql.OutParameter
import groovy.sql.Sql
import oracle.jdbc.OracleTypes
import java.sql.ResultSet
def driver = 'oracle.jdbc.driver.OracleDriver'
def sql = Sql.newInstance('jdbc:oracle:thin:#MY-SERVER:1521:XXX', 'usr', 'psw', driver)
// special OutParameter for cursor type
OutParameter CURSOR_PARAMETER = new OutParameter() {
public int getType() {
return OracleTypes.CURSOR;
}
};
// look at some ceremonial wrappers around anonymous block
String sqlString = """{call
DECLARE
my_cur SYS_REFCURSOR;
x VARCHAR2(32767) := ?;
BEGIN
OPEN my_cur
FOR
SELECT x || level AS my_column FROM dual CONNECT BY level < 10;
? := my_cur;
END
}
""";
// the order of elements matches the order of bindings
def parametersList = ["abc", CURSOR_PARAMETER];
// rs contains the result set of cursor my_cur
sql.call(sqlString, parametersList) { ResultSet rs ->
while (rs.next()) {
println rs.getString("my_column")
}
};

Xquery ERROR err:XPDY0002: undefined value for variable $skill

I am trying to use xquery for a project and I cannot see why this query is not working. It gives me the following error:
err:XPDY0002: undefined value for variable $skill
I am new to xquery and I am using EXIST DB as a database and I have tried using base x db and this works there perfectly. Is there anything i am missing in existdb? Any help would be appeciated.
for $endorsement in doc('/db/users.xml')/LOUser/Endorsements
for $endorsed_skill in $endorsement/Skills
let $skill := $endorsed_skill/text()
for $user in doc('/db/users.xml')/LOUser/User[#URL = $endorsement/URL2/text()]
let $Name := $user/Name/text()
where not($user/Skills/text() = $skill)/* I am getting the error here*/
group by
$Name, $skill
return {$Name}