I have to copy data from one table(main_tbl) to another table(sub_tbl)
CREATE OR REPLACE FUNCTION auditlogfunc() RETURNS TRIGGER AS
$example_table$
DECLARE
temp text;
BEGIN
temp = 'SELECT device_id FROM company ORDER BY id DESC LIMIT 1';
INSERT INTO temp(emp_id, entry_date, name,age) VALUES(new.id,current_timestamp, new.name, new.age);
RETURN NEW;
END;
$example_table$ LANGUAGE plpgsql;
temp = 'SELECT device_id FROM company ORDER BY id DESC LIMIT 1'; this will select the last value from main_tbl and stored into temp variable.
Now I want to copy data from main_tbl to temp table..
ERROR: relation "temp" does not exist
#a_horse_with_no_name has already pointed out how to do this. If i understood correctly, you dv002 table is already created.
CREATE OR REPLACE FUNCTION auditlogfunc ()
RETURNS trigger AS
$body$
DECLARE
get_last_value integer;
your_table_name text := 'dv002';
BEGIN
SELECT id into get_last_value FROM tb_main_table ORDER BY id DESC LIMIT 1;
EXECUTE format('insert into %s(emp_id, entry_date, name,age) VALUES ($1,$2,$3,$4,$5)', your_table_name) using get_last_value,new.id,current_timestamp, new.name, new.age;
RETURN new;
$body$
LANGUAGE plpgsql;
See here how to store the result of a query in a variable.
See here how to execute a string as an SQL command.
Use the quote_ident() function on the variable before including it as identifier in an SQL query string. That way you are safe from SQL injection.
Related
I am trying to execute a Stored Procedure which updates a column and retrieves the filename from the same table after updating
StoredProcedure:
CREATE DEFINER=`test`#`%` PROCEDURE `update_count`(
IN in_testID VARCHAR(64),
OUT out_FileName VARCHAR(100),
OUT out_Message VARCHAR(100))
BEGIN
UPDATE files SET count=count+1 WHERE testID=in_testID;
SELECT FileName INTO out_FileName FROM files WHERE testID = in_testID;
SET out_Message = 'File updated uccessfully';
END
JavaCode to execute this StoredProcedure:
Query query = session.createSQLQuery("CALL update_count(:in_testID, #out_FileName, #out_Message)").addEntity(FilesBean.class)
.setParameter("in_testID",body.getTestId());
query.executeUpdate();
Updated the query.executeUpdate() with query.list(). But the line returning a error ResultSet is from UPDATE. No Data
I need to fix this with using the createSQLQuery
The easiest way to do that is return the out parameter as part of the returning parameters (relevant only if you have access to the store procedures).
just add a store procedure like the following one
create procedure myProcedure_only_in_prams (
in in_Id int)
begin
call myProcedure(in_id,#out_Id) ;
select #out_id
END;
after done that it quite simple to use it with Hibernate in the following way
Query query = session.createSQLQuery(
"CALL myProcedure_only_in_parms (:in_Id)")
.setParameter("in_id", 123);
List result = query.list();
The result contains the out parameter, if you want return multiply parameters you can add it by doing select #parm1,#parm2,... ,#parmn
Hope it helped
I'm trying to create a stored procedure in a MySQL database using the contents of a text file:
USE myDatabase;
DROP PROCEDURE IF EXISTS myStoredProcedure;
DELIMITER $$
CREATE PROCEDURE myStoredProcedure
(
_description VARCHAR(50),
_value INT
)
BEGIN
INSERT INTO myTable
(
description,
value
) VALUES (
_description,
_value
);
SELECT
id,
description,
value
FROM myTable
WHERE id = LAST_INSERT_ID();
END;
$$
DELIMITER ;
I execute the SQL using a native query:
Query query = entityManager.createNativeQuery(queryText);
...
query.executeUpdate();
But it gets an error on the DROP PROCEDURE
I commented out the DROP PROCEDURE and then it gets an error on the DELIMITER
Basically, it gets an error on any line after the first semicolon.
It seems as if JPA hibernate is parsing my query and telling me there's a problem with it rather than passing the unadulterated text onto MySQL.
The sql runs in MySQL without error.
I can't find anything in Google about creating a stored procedure with JPA, only calling one.
Does anyone have any insight on what I might be doing wrong? Or if this is even possible.
This can be possible if you mention the following property in the url
spring.datasource.url=jdbc:mysql://localhost:3306/test?allowMultiQueries=true
The allowMultiQueries will instruct the driver to sent delimited queries to the database.
Please note that if you are using native queries be-aware of sql injection attack.
You dont need to put the delimiter(DELIMITER) explicitly.The sql statement
The following query works
SET myDatabase;
DROP PROCEDURE IF EXISTS myStoredProcedure;
CREATE PROCEDURE myStoredProcedure ( _description VARCHAR(50), _value INT )
BEGIN
INSERT INTO
myTable ( description, value )
VALUES ( _description, _value );
SELECT id, description, value
FROM myTable
WHERE id = LAST_INSERT_ID();
END;
I am working with TSP(Traveling salesmen problem) Solution in mysql.
for that we are going to develop procedure where i want to execute following query
-- variable coming from java
CREATE PROCEDURE solve_tsp(
inout ids varchar(21845);
)
begin
declare ret_ids varchar(21845);
-- some code
while length(ids) > 0 do
-- some assignment
SELECT to_id,distance into #l_tmp_id,#l_distance FROM mst_distance_matrix WHERE from_id =',#l_tmp_id,' AND
to_id IN (ids) -- ids is variable contains comma delimited string.
order by distance desc limit 1
-- concat value of to_id in ret_ids variable and then remove from ids variable
end while;
select ret_ids;
end;
You should look here.
http://dev.mysql.com/doc/refman/5.0/en/sql-syntax-prepared-statements.html
Example:
PREPARE stmt1 FROM 'SELECT SQRT(POW(?,2) + POW(?,2)) AS hypotenuse';
SET #a = 3;
SET #b = 4;
EXECUTE stmt1 USING #a, #b;
DEALLOCATE PREPARE stmt1;
See also:
Dynamic Query in MySQL
My MyBatis select is
// result map that sub-selects a folder
<resultMap id="beanWithFolderMap" type="com.example.BeanWithFolder">
<id column .../>
<association column="folder_id" property="folder" javaType="com.example.Folder" select="selectFolder"/>
</resultMap>
// folder sub-select
<select id="selectFolder" resultType="com.example.Folder">
SELECT
folder_id
name,
FROM folders
WHERE folder_id=#{folderId}
</select>
When no rows matching folder_id are found I want to return a special instance of Folder class.
Right now MyBatis returns null when it can't find a row. I want to return a Folder instance with folderId field set - since I know what I'm looking for I can at least set this field.
How to do it?
something like
SELECT
#{folderId} as folder_id,
name,
FROM folders
WHERE folder_id=#{folderId}
would be great, but I get the exception "Could not determine data type of parameter $1"
Function
If this query is used frequently, I would create a small function for it. That's probably fastest:
CREATE OR REPLACE FUNCTION f_foo(_folder_id int)
RETURNS TABLE (folder_id int, name text) AS
$func$
BEGIN
RETURN QUERY
SELECT f.folder_id, f.name
FROM folders f
WHERE f.folder_id = $1;
IF NOT FOUND THEN -- only if nothing was found
RETURN QUERY
VALUES ($1, NULL); -- columns must match!
END IF;
END
$func$ LANGUAGE plpgsql STABLE;
Call:
SELECT * FROM f_foo(133)
That's what you use in your script. Just like selecting from a table.
Plain SQL
There are other ways with plain SQL, preferably using NOT EXISTS. I guess a CTE would help:
WITH x AS (
SELECT folder_id, name
FROM folders
WHERE folder_id = $1;
)
SELECT * FROM x
UNION ALL
SELECT $1, NULL
WHERE NOT EXISTS (SELECT 1 FROM x);
I'm trying to create a stored procedure that will be used by a client application to search for customers in a customers table and then return all the info about the customer if he's found. I've created a procedure to add a customer to the table:
DELIMITER $
CREATE PROCEDURE `add_cust` (IN custF VARCHAR(100), IN custL VARCHAR(100))
BEGIN
INSERT INTO customers (cFirst, cLast) VALUES(custF, custL);
END $
And it works.
My customers table is very simple - an auto-incrementing primary key, fist and last name columns.
I can't wrap my head around this other search procedure. The way I see it is to have two procedures for searching. One procedure uses First Name to search for customer, and the second one will use Last Name.
I assume I'll have to use a cursor FOR SELECT with WHERE clause, and a WHILE loop. But how do I return the result to the client application? Do I declare one of the parameters in the stored procedure as OUT? Or do I just declare one parameter as INOUT?
So far this is where I am at:
DELIMETER $
CREATE PROCEDURE `searchCustByFirst` (IN custF VARCHAR(100))
BEGIN
END $
It is very simply -
CREATE PROCEDURE searchCustByFirst(IN custF VARCHAR(100))
BEGIN
SELECT cFirst, cLast FROM customers WHERE cFirst = custF;
END
This procedure will return dataset, just read it in the application.
Another solution is to use OUT parameters, for example -
CREATE PROCEDURE searchCustByFirst(IN custF VARCHAR(100), OUT custL VARCHAR(100))
BEGIN
SELECT cLast INTO custL FROM customers WHERE cFirst = custF;
END
In this case SELECT statement cannot return more then one record, so criteria field cFirst should be unique.