I have created a single procedure for update for different table say country & department.
and in procedure i'hve mentioned an input parameter for table name along with other parameter.
But unfortunately i got an error. Here is mySql Procedure:
CREATE DEFINER=`satish`#`%` PROCEDURE `p_update_Master_Name`(
IN tbl_Name VARCHAR(35),
IN tbl_column_old_value VARCHAR(35),
IN tbl_column_new_value VARCHAR(35),
IN tbl_user_id INT,
OUT msg INT
)
BEGIN
IF EXISTS (SELECT Name from tbl_name where Name = tbl_column_new_value) then
SET msg := '1';
-- failed case
else
UPDATE tbl_name SET Name= tbl_column_value, Modified_Date=now(), Modified_by=tbl_user_id where Name = tbl_column_old_value;
set msg := '0';
-- success
END IF;
END
Im calling this procedure from java file.
CallableStatement cs = conn.prepareCall("{ call p_update_Master_Name(?,?,?,?,?)}");
cs.setString(1, "country");
cs.setString(2, real);
cs.setString(3, mod);
cs.setInt(4, 01);
cs.execute();
cs.registerOutParameter(5, Types.INTEGER);
int i=cs.getInt(5);
but it gives me a mysql.jdbc exception.
com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: Table 'sims.tbl_name' doesn't
exist
Please help me. Thanx in advance
You can't use variables to define table or column (or any other db object for that matter) names in static SQL queries. They should be literals.
You have to use dynamic SQL to achieve your goal. Read more on the topic SQL Syntax for Prepared Statements
Your stored procedure might look like
DELIMITER $$
CREATE PROCEDURE p_update_Master_Name
(
IN tbl_Name VARCHAR(35),
IN tbl_column_old_value VARCHAR(35),
IN tbl_column_new_value VARCHAR(35),
IN tbl_user_id INT,
OUT msg INT
)
BEGIN
SET #sql = CONCAT('SELECT (COUNT(*) > 0) INTO #result FROM ', tbl_name, ' WHERE Name = \'', tbl_column_new_value, '\'');
PREPARE stmt FROM #sql;
EXECUTE stmt;
SET msg = #result;
IF #result = 0 THEN
SET #sql = CONCAT('UPDATE ', tbl_name,
' SET Name = \'', tbl_column_new_value,
'\', Modified_Date = NOW(), Modified_by = ', tbl_user_id,
' WHERE Name = \'', tbl_column_old_value, ' \'');
PREPARE stmt FROM #sql;
EXECUTE stmt;
END IF;
DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;
Here is SQLFiddle demo
It seems there is some error with the procedure syntax
wrong one:
1. SELECT Name from *tbl_name* where Name = tbl_column_new_value) then
SET msg := '1'
In the above line of code you didn't set any value to tal_name;
You can refer the below syntax concentrate on INTO in the query:
CREATE OR REPLACE PROCEDURE getDBUSERByUserId(
p_userid IN DBUSER.USER_ID%TYPE,
o_username OUT DBUSER.USERNAME%TYPE,
o_createdby OUT DBUSER.CREATED_BY%TYPE,
o_date OUT DBUSER.CREATED_DATE%TYPE)
IS
BEGIN
SELECT USERNAME , CREATED_BY, CREATED_DATE
INTO o_username, o_createdby, o_date
FROM DBUSER WHERE USER_ID = p_userid;
END;
Related
I want to use procedure multiple times to get many table select from oracle database
My Oracle procedure
PROCEDURE getInfo(
Status IN VARCHAR2,
P_CUR OUT REFCURSOR)
AS
BEGIN
OPEN P_CUR FOR
SELECT *
FROM TABLE
WHERE TABLE.STATUS = Status
END;
Here is my Java call the the procedure. It doesn't work, I can not set registerOutParameter for PreparedStatement to get the cursor data.
PreparedStatement pstmt = null;
pstmt = cnn.prepareCall("{call " + schemaName + ".LOC_EXCHANGE.getInfo(?,?)}");
for (Entity entity : ListEntity) {
int i = 1;
pstmt.setString(i++, entity.getTxnId());
pstmt.registerOutParameter(i, OracleTypes.CURSOR);
pstmt.addBatch();
}
pstmt.executeBatch();
cnn.commit();
rs = (ResultSet) pstmt.getObject(i);
Fetching the data in bulk rather than in batch
I don't think you can batch those calls. You could probably do an anonymous block, instead:
BEGIN
LOC_EXCHANGE.getInfo(?, ?);
LOC_EXCHANGE.getInfo(?, ?);
LOC_EXCHANGE.getInfo(?, ?);
...
END;
Avoiding N+1
Personally, I think you're producing an N+1 problem here. rather than fetching data for each individual entity.getTxnId(), how about refactoring your getInfo() procedure to allow for returning data for a list of txnids? Do this:
CREATE TYPE txnids AS TABLE OF VARCHAR2(4000);
And then declare:
PROCEDURE getInfo(
Status IN txnids ,
P_CUR OUT REFCURSOR)
AS
BEGIN
OPEN P_CUR FOR
SELECT *
FROM TABLE
WHERE TABLE.STATUS IN (
SELECT * FROM TABLE (Status)
)
ORDER BY TABLE.STATUS
END;
Since you're projecting *, you'll still be able to access the STATUS column in order to group data in the client, after fetching it all.
drop PROCEDURE if exists insert_poo;
DELIMITER $$
CREATE PROCEDURE insert_poo(IN barcode varchar(250),IN qty float,IN amount float,IN vat float,IN
description varchar(250),IN clrk_code varchar(20),IN mechno varchar(20),IN bill_date datetime)
BEGIN
DECLARE unit_pric float;
DECLARE itemcode varchar(150);
SET unit_pric =(select retail1 FROM `mytable` WHERE `mytable`.barcode = barcode);
SET itemcode =(select prod_id FROM `mytable` WHERE `mytable`.barcode = barcode);
INSERT into mytable2(clrk_code,tran_code,tran_desc,tran_qty,unit_price,tran_amt,bill_date,tax)values(clrk_code,barcode,description,qty, unit_pric,amount,bill_date,vat)
END $$
DELIMITER ;
Kindly help with any solution on how to create and call it. thanks in advance
Probably you can use the following example as a reference:
The below one is the Store Procedure itself:
connect anyDbName/anyDbName
CREATE OR REPLACE PROCEDURE any_storeProcedure_name
-- Following are some example parameters you may use in your SP
(
id varchar2,
name_param varchar2,
-- The control status of the operation
statusOperation_out OUT VARCHAR2
)
AS
BEGIN
statusOperation_out := 'in_proccess';
insert into property_name values('Name', id, name_param);
COMMIT;
statusOperation_out := 'ok';
EXCEPTION
WHEN OTHERS THEN
statusOperation_out := 'error';
ROLLBACK;
END;
/
And the following is the Java method call that is using the previous SP:
public long addProperties(String id, String name) {
//The string sql syntax for calling the store procedure
String sql = "{CALL any_storeProcedure_name("
+ "id => ?, "
+ "name => ?)}";
try (Connection conn = CreateConnection.getDSConnection();
CallableStatement cs = conn.prepareCall(sql)) {
//The following are the parameters for the store procedure
cs.setString (1, id);
cs.setString (2, name);
//Following are the parameters to get some outputs from the store procedure
cs.registerOutParameter(3, Types.VARCHAR);
cs.executeQuery();
//The return varible from the store procedure is the one
//that is being used for feedback on whether the SP ran fine.
if (cs.getString(3).equalsIgnoreCase("ok")) {
System.out.println("Feedback from SP is: " + cs.getString(3));
return 1;
} else {
return 0;
}
} catch (SQLException e) {
e.printStackTrace();
return 0;
}
}
So hope this can give some reference, by the way the DB I'm using is Oracle 11g. But I recall it's very similar to MySQL DB.
I am trying to run the following SQL script using Java and am getting issues with no resultset from JDBCTemplate. I thought about reducing it using functions/stored procedures and would like some help with it:
SQL - first part:
SET NOCOUNT ON
IF OBJECT_ID('tempdb.dbo.#tempSearch', 'U') IS NOT NULL
DROP TABLE #tempSearch;
CREATE TABLE #tempSearch
(
ID INT,
Value VARCHAR(255)
)
INSERT INTO #tempSearch
VALUES (1, 'Variable1'), (2, 'Variabl2');
Second part:
WITH cte AS
(
SELECT
RoleID,
',' + REPLACE(REPLACE(GroupNames, ',', ',,'), ' ', '') + ',' GroupNames
FROM
UserGroup_Role_Mapping
), cte2 AS
(
SELECT
cte.RoleID,
REPLACE(cte.GroupNames, ',' + Value + ',', '') AS GroupNames,
s.ID, s.Value
FROM
cte
JOIN
#tempSearch s ON ID = 1
UNION ALL
SELECT
cte2.RoleID,
REPLACE(cte2.GroupNames, ',' + s.Value + ',', '') AS l,
s.ID, s.Value
FROM
cte2
JOIN
#tempSearch s ON s.ID = cte2.ID + 1
)
SELECT
a.Role, a.Sort_Order,
a.Parent, a.Parent_ID, a.Parent_URL,
a.Child, a.Child_ID,a.Child_URL
FROM
Config_View a
WHERE
a.Role IN (SELECT Name
FROM
(SELECT DISTINCT RoleID FROM cte2 WHERE LEN(GroupNames) = 0) tempRoles
JOIN
User_Role ON tempRoles.RoleID = User_Role.ID
)
DROP TABLE #tempSearch
I was thinking first part can be done in a stored procedure. I did read here (stored procedure with variable number of parameters) about making a table from a list of variables but am not sure how to do set those variables in a loop like i am doing from above (1,Variable1 etc.).
I think the second part can be by itself?
So my updated query might be:
Call stored procedure (variable1, ..., variablex);
SQL part 2?
If anyone can help that would be great!
It's possible to do this in two seperate batches, but only if you can ensure that the first batch runs in session scope, and not in a nested batch ( eg via sp_executesql ). Temp tables created in nested batches, like stored procedures or prepared statements are automatically destroyed at the end of the nested batch. So it depends on how you call it. My guess is that a PreparedStatement won't work.
The right way to do this is probably to use a stored procedure with a table-valued parameter, or a JSON (for SQL 2016+), or XML parameter and parses it in the stored procedure body. See https://learn.microsoft.com/en-us/sql/connect/jdbc/using-table-valued-parameters?view=sql-server-2017
You can also use a TSQL batch instead of a stored procedure and bind a Table-Valued Parameter, or a NVarchar(max) parameter containing JSON.
With a TVP you could simply use a batch like:
with s as (
select * from ? --bind a table-valued parameter here
), cte as (
select RoleID,','+replace(replace(GroupNames,',',',,'),' ','')+',' GroupNames from UserGroup_Role_Mapping
)
,cte2 as(
select cte.RoleID, replace(cte.GroupNames,','+Value+',','') as GroupNames, s.ID, s.Value
from cte
join s on ID=1
union all
select cte2.RoleID, replace(cte2.GroupNames,','+s.Value+',','') as l, s.ID ,s.Value
from cte2
join s on s.ID=cte2.ID+1
)
SELECT a.Role, a.Sort_Order, a.Parent, a.Parent_ID, a.Parent_URL, a.Child, a.Child_ID,a.Child_URL
FROM Config_View a
WHERE a.Role IN (
Select Name from (
Select distinct RoleID from cte2 where len(GroupNames)=0
) tempRoles
join User_Role
on tempRoles.RoleID = User_Role.ID
)
That would be the value of the string variable sql, and then call it something like:
SQLServerPreparedStatement pStmt = (SQLServerPreparedStatement) connection.prepareStatement(sql);
pStmt.setStructured(1, "dbo.CategoryTableType", sourceTVPObject);
ResultSet rs = stmt.executeQuery();
Iam trying to send an integer value from mysql Procedure which must be recieved by Java class. this i'hv done
CREATE DEFINER=`root`#`localhost` PROCEDURE `updateCountry`(o_name varchar(35), u_name varchar(50),m_by varchar(35),out msg int)
BEGIN
if not exists (select country from country where country = u_name) then
UPDATE country SET country= u_name, modify_date=now(), modify_by=m_by where country = o_name;
end if;
if exists (select country from country where country = u_name) then
set msg := '1';
end if;
END
and my java class is :
public void modifyCountry(String mod, String real, String crby)throws Exception {
Date d = new Date(System.currentTimeMillis());
System.out.print(d);
CallableStatement cs = conn
.prepareCall("{ call updateCountry(?,?,?,?)}");
cs.setString(1, real);
cs.setString(2, mod);
// cs.setDate(3, d);
cs.setString(3, crby);
cs.registerOutParameter(4, Types.INTEGER);
int check = cs.getInt(4);
System.out.print(check);
cs.execute();
}
And this is the error which im getting
No output parameters returned by procedure.
Try to execute the statement first then read the output parameter
I have written a function that I would like to call in Java. But I don't think it is able to do anything with the query that I passed. Following is my code from java:
String QUERY_LOCATION = "select (license_plate) as test from carInst( (select category_name from reservation where rid = ?) , (select lname from reservation where rid = ?))";
//PreparedStatement check_location = null;
PreparedStatement check_location = connection.prepareStatement(QUERY_LOCATION);
check_location.setInt(1, rid);
check_location.setInt(2, rid);
rs = check_location.executeQuery();
if (rs.next()) {
System.out.print("Car found: "+rs.getString("test")+"\n");
license_plate = rs.getString("test");
update_reservation.setString(5, license_plate);
bool = false;
} else {
System.out
.print("There is no car available\n");
}
And following is my stored procedure written in PL/pgSQL (PostgreSQL):
CREATE OR REPLACE FUNCTION carInst(cname varchar(20), loc varchar(20) )
RETURNS TABLE (license_plate varchar(6) ) AS $$
BEGIN
DECLARE cur CURSOR
FOR SELECT carinstance.license_plate, carmodel.category_name, carinstance.lname FROM carinstance,carmodel
WHERE carinstance.mid = carmodel.mid ;
BEGIN
FOR rec IN cur LOOP
RETURN QUERY SELECT distinct carinstance.license_plate FROM Carinstance
WHERE rec.category_name = cname
AND rec.lname = loc
AND rec.license_plate=carinstance.license_plate;
END LOOP;
END;
END;
$$ LANGUAGE plpgsql;
When I run the code in Java, the print statement prints a null value for Car found. I would really appreciate some help here.
Problems
Most importantly, the query in the LOOP is nonsense. You select rows from carinstance, but all conditions are on rec. This select all rows multiple times.
One END too many. FOR has no END, only LOOP has.
Whenever you feel the temptation to work with an explicit cursor in plpgsql, stop right there. Chances are, you are doing it wrong. A FOR loop has an implicit cursor anyway.
Don't mess with mixed case identifiers without double quotes. I converted all identifiers to lower case.
You use one simple query, spread out over a cursor and another query. This can all be much simpler.
Solution
Try this simple SQL function instead:
CREATE OR REPLACE FUNCTION car_inst(_cname text, _loc text)
RETURNS TABLE (license_plate text)
LANGUAGE sql AS
$func$
SELECT DISTINCT ci.license_plate
FROM carmodel cm
JOIN carinstance ci USING (mid)
WHERE cm.category_name = $1
AND ci.lname = $2
$func$;
Call:
SELECT license_plate AS test FROM car_inst(
(SELECT category_name FROM reservation WHERE rid = ?)
, (SELECT lname FROM reservation WHERE rid = ?)
);
Or build it all into your function:
CREATE OR REPLACE FUNCTION car_inst(_cname text, _loc text)
RETURNS TABLE (license_plate text)
LANGUAGE sql AS
$func$
SELECT DISTINCT ci.license_plate
FROM carmodel cm
JOIN carinstance ci USING (mid)
JOIN reservation r1 ON r1.category_name = cm.category_name
JOIN reservation r2 ON r2.lname = ci.lname
WHERE r1.rid = $1
AND r2.rid = $2;
$func$;
Call:
"SELECT license_plate AS test FROM car_inst(? , ?)";
Remember: The OUT parameter license_plate is visible anywhere in the body of the function. Therefore you must table-qualify the column of the same name at all times to prevent a naming collision.
DISTINCT may or may not be redundant.