DELIMITER //
CREATE PROCEDURE temp ( empId INT)
BEGIN
DECLARE var_etype VARCHAR(36);
SELECT
emptype = QOUTE(emptype)
FROM
dms_document
WHERE
id = empid;
SELECT
emptype,
CASE
WHEN emptype = 'P' THEN doctype
ELSE 'No Documents required'
END
FROM
dms_report
WHERE
pilot = 1;
End//
DELIMITER ;
I have created this procedure successfully but when I try to call it, I am getting error 1305 the function database.temp does not exist. I am trying to call using this statement:
SET #increment = '1';
select temp( #increment)
but I get Error, please tell me where I made mistake.
This is how you call it, use use the keyword call and then procedure's name
call procedureName(params);
in call of making an string
String sqlString = "procedureName("+?+")"; //in case of Integers
String sqlString = "procedureName('"+?+"')";//in case of Integers
bring the parameter in prepared statement.
MySQL's documentation on Using JDBC CallableStatements to Execute Stored Procedures explains the necessary steps quite well.
This is what your java code needs to look like:
CallableStatement cStmt = conn.prepareCall("{call temp(?)}");
cStmt.setInt(1, 42); //set your input parameter, empId, to 42.
If you want to work with the rows returned by your stored procedure's query in your Java code, you're also going to need to create an OUT parameter as noted in MySql's documentation page titled, CALL Syntax:
CALL can pass back values to its caller using parameters that are
declared as OUT or INOUT parameters
In order to call your stored procedure from MySQL workbench, use the CALL command. You can call stored procedure by directly setting values for each of the parameters:
SET #increment = 1;
CALL temp(#increment)
Then you simply use the SELECT statement to return the value of your output parameter
SELECT #outParameter
With help setting your output parameters, please read the article MySQL Stored Procedure - SELECT - Example.
Your stored procedure is syntactically wrong, and as mentioned in the comments, you're not using the stored procedure functionality for it's intended use. It's intended to be used for data manipulation not for querying. You should instead consider turning your procedure into a series of prepared statements.
Please let me know if you have any questions!
Related
I'm trying to use a table-valued parameter for a stored procedure we're calling using Hibernate's Session.createSQLQuery.
I have created a type and stored procedure in SQL:
CREATE TYPE StringListType AS TABLE
(
StringText NVARCHAR(256)
)
CREATE PROCEDURE [dbo].[TestStringListType]
(
#stringList StringListType READONLY
)
AS
SELECT * FROM #stringList
I can use this in SQL with:
BEGIN
Declare #StringListTemp As StringListType
insert INTO #StringListTemp (StringText)
values ('foo'), ('bar'), ('baz')
EXEC TestStringListType #StringListTemp
END
What I would like to do in Java is something like:
String fakeQueryStr = "call TestStringListType :list";
SQLQuery fakeQuery = getSession().createSQLQuery(fakeQueryStr);
ArrayList<String> data = Lists.newArrayList("foo", "bar", "baz");
fakeQuery.setParameter("list", data);
return fakeQuery.list();
Neither setParameter or setParameterList work here of course. How do I map my list of Strings to this type to use as a parameter?
I was unable to find a solution for this problem as written. My work-around was to copy the entirety of the stored procedure into a string in Java. In the above example, that would mean that I replaced:
String fakeQueryStr = "call TestStringListType :list";
with
String fakeQueryStr = "SELECT * FROM :list";
In my actual code, this was undesirable, because the stored procedure was a significantly longer set of statements, but it does still work when wrapped in BEGIN and END within the string.
I'm struck with an issue where am trying to call an Oracle stored procedure using Hibernate as in the below snippets.
My DAO class:
Query q = session.createSQLQuery(" {call PKG.PROC_GET_DATA_SET(?, :parameter1, :parameter2) }")
.setParameter(0, OracleTypes.CURSOR)
.setParameter("parameter1", "fDate")
.setParameter("parameter2", "tDate");
resultSet = q.list();
PROCEDURE:
CREATE OR REPLACE PACKAGE BODY schema.PKG
AS
PROCEDURE PROC_GET_DATA_SET(
P_CURSOR OUT SYS_REFCURSOR,
P_STRING1 IN VARCHAR2,
P_STRING2 IN VARCHAR2
)
AS
BEGIN
OPEN P_CURSOR FOR
.
.
.
But when i call the proc as in the DAO class, am getting an error as below.
Error:
PLS-00306: wrong number or types of arguments in call to 'PROC_GET_DATA_SET'
ORA-06550: line 1, column 7:
PL/SQL: Statement ignored
Struggling to spot the reason. Can someone throw some light here please?
TIA,
You cannot use this code to call a procedure using hibernate. See docs
The recommended call form is standard SQL92: { ? = call
functionName() } or { ? = call
procedureName(}. Native call syntax is not supported.
For Oracle the following rules apply:
A function must return a result set. The first parameter of a
procedure must be an OUT that returns a result set. This is done by
using a SYS_REFCURSOR type in Oracle 9 or 10. In Oracle you need to
define a REF CURSOR type. See Oracle literature for further
information.
I suggest trying this:
{? = call PKG.PROC_GET_DATA_SET(?, ?) }
If this does not work, use session.connection()
I have written some code calling the mysql procedure in jdbc
Driver requires declaration of procedure to either contain a '\nbegin' or '\n' to follow argument declaration, or SELECT privilege on mysql.proc to parse column types.
am getting above error when i call procedure below is the code:
CallableStatement proc;
if (JDBCConnection.connection != null) {
Connection con = JDBCConnection.getConnection();
System.out.println("in DAOimpl "+username);
proc= con.prepareCall("{call getChildList(?) }");
System.out.println("prosedure"+proc);
proc.setString(1,username);
System.out.println(proc);
ResultSet rs=proc.executeQuery();
}
please give me the solution it is help ful for me.
The error message is quite clear:
Driver requires declaration of procedure to either contain a '\nbegin' or '\n' to follow argument declaration, or SELECT privilege on mysql.proc to parse column types.
So that tells us:
Your stored procedure declaration doesn't contain \nbegin or doesn't have an \n after the argument(s) declaration; or
The user you're using to call the statement doesn't have SELECT privilege on the stored procedure.
So step 1 is to figure out which of those two things it is.
To fix #1, put the body of the sproc in begin and end. So for instance, if your sproc is currently (altering an example from the MySQL docs a bit):
CREATE PROCEDURE proc(IN inputParam VARCHAR(255))
SELECT CONCAT('zyxw', inputParam);
Change it to
CREATE PROCEDURE proc(IN inputParam VARCHAR(255))
BEGIN
SELECT CONCAT('zyxw', inputParam);
END
To fix #2, grant the SELECT privilege on the sproc to the user.
I am using simpleJDBCTemplate to insert a value to a postgre database.
String sql "insert into testTable values(:bla, :blah, functionThatTakesAText(':blu'))"
BeanPropertySqlParameterSource namedParameters = new BeanPropertySqlParameterSource(lighting);
simpleJdbcTemplate.update(sql, namedParameters);
Now, the blu parameter is actually a number(the actual sql takes 2 real's ) that is read from a file given by the client.
As a result the database receives something like the following:
insert into testTable values(?, ?, functionThatTakesAText(':blu'))
and fails to replace the :blu parameter as expected.
The current workaround that I'm using is replacing the blu parameter with its value using a regex, but I'm unsure on how safe that is.
How would you solve that?
Spring will skip over anything inside quotes in the SQL (see the skipCommentsAndQuotes() method of NamedParameterUtils), on the basis that anything inside quotes shouldn't be touched.
That makes sense in this context - you would want the prepared statement to say
functionThatTakesAText(?)
rather than
functionThatTakesAText('?')
Try removing the quotes there, and the placeholder should be substituted correctly.
I'm connecting to SQL Server (2005) through Java using the Microsoft SQL Server JDBC Driver 2.0.
How do I get the return value from a stored procedure? I'm doing something like:
Connection connection = dataSource.getConnection()
CallableStatement proc = connection.prepareCall("{ call dbo.mySproc() }");
proc.execute();
Should I be using execute()? executeQuery()? executeUpdate()? None of these seem to return a return value by default but I'm not really sure how to get to it.
EDIT 1: To be clear, I know how to call stored procedures. This question is specifically about how to get the RETURN VALUE (as opposed to a Result Set). The Return Value is an integer that is usually generated when you execute a query with no Result Set or if you specifically state something like RETURN 0 in your SQL.
EDIT 2: executeUpdate() returns an int but this int is not the same as the Return Value. Also, an OUT parameter is not the same as a return value.
Bozho's 2nd revised answer was close but not quite there. It did lead me to the answer though.
Taking the code example I started with we end up with:
CallableStatement proc = connection.prepareCall("{ ? = call dbo.mySproc() }");
proc.registerOutParameter(1, Types.INTEGER);
proc.execute();
int returnValue = proc.getInt(1);
The key pieces here are the "? =" in front of the "call" in the prepareCall function which sets up a place for the return value and the registerOutputParameter. It has to be registered as an Integer, as the return value is always an int (at least in SQL Server, maybe it's different in other DBs). You therefore have to get it using getInt. I tested this method and it does work.
c.prepareCall("? = ..");
cs.execute();
String returnedValue = cs.getString(1);
(or the method of the appropriate type. You can use getObject alternatively)
From an old getting started tutorial
the getXXX methods in CallableStatement retrieve values from the OUT parameters and/or return value of a stored procedure.
(Btw, the links that were provided by Umesh had this sort of information.)