common values between two call statements in MySQL - mysql

the problem is, I have a procedure which returns a set of values and the column name returned by that procedure is friend, it accepts 1 parameter that is username,
now I have two queries:
call test('nishchal') and call test('nootan') now I want the common values returned by these two procedure, any solution guys??
My procedure has these lines of codes
begin
select u_name` as friend
from table_name
where f_id = username
end
where username is the parameter passed

It's a bit clunky but you could put the results into a temporary table.

Related

MySQL Aggregate GROUP_CONCAT and JSON_ARRAYAGG functions returning duplicate values inside stored procedure

Aggregate functions are working for my on command line and in my SQL client, but when I run those very same aggregate functions for use in setting a variable inside a stored procedure, I get duplicate values - the same number of values for multiple rows, but all values are the same.
Say I have a table `table_name`:
|test_field | target_field|
|----------------:|:------------|
|"test_value" |1 |
|"test_value" |2 |
|"not_test_value" |3 |
|"test_value" |4 |
The aggregate function works as expected in regular SQL query:
SET #array_value := "";
SELECT GROUP_CONCAT(target_field) INTO #array_value
FROM `table_name`
WHERE `test_field` = 'test_value';
Where I get the result:
"1,2,4"
However, when I use same syntax inside a stored procedure, I get very different results:
"4,4,4"
Note that this stored procedure is triggered on an update of the same table:
CREATE TRIGGER `cacheAggregate`
AFTER INSERT ON `table_name`
FOR EACH ROW
BEGIN
CALL storedProcedureName (
NEW.target_field
);
END
...which calls the following stored procedure:
CREATE PROCEDURE `storedProcedureName `(
IN `target_field` VARCHAR
)
BEGIN
SET #answer_array := '';
SELECT GROUP_CONCAT(target_field) INTO #answer_array
FROM `table_name`
WHERE `test_field` = "test_value";
INSERT INTO CACHE_TABLE (`answers_array`, `fk_target_field`)
VALUES(#answer_array, target_field);
END
When I insert a value into the table, the trigger fires, calls the stored procedure, but the issue presents itself - #answer_array is wrong, consisting of a an array of the correct length, where each value is always the last value entered into the table.
IE, If I run this query:
INSERT INTO `table_name` (`test_field`,`target_field`) VALUES ("test_value", 5);
I would expect it to be stored as:
"1,2,4,5"
However, what is actually being returned is:
"5,5,5,5"
My guess is that the stored procedure is using some kind of cursor/pointer which breaks the aggregate function, but I had trouble finding anyone who had the same issue.
UPDATE/RESOLVED
While trying to reproduce this with the modified example code, I found my issue.
I'm leaving this here in case it helps anyone out in the future.
The issue was a naming collision. The parameter name for my stored procedure was the same as the target_field of my table, so the SELECT statement was using the stored procedure parameter as opposed to the table field. Since the value passed to the stored procedure the last updated value sent by the trigger, it was replicated the number of the resultant rows.
It would be the same if I used a literal in a select statement that returned multiple rows, EG:
SELECT GROUP_CONCAT("String Literal") INTO #answer_array
FROM `table_name`
WHERE `test_field` = "test_value";
...would produce the result:
"String Literal,String Literal,String Literal,String Literal"
The solution was to either explicitly set the table name in the GROUP_CONCAT argument:
SELECT GROUP_CONCAT(tn.target_field) INTO #answer_array
FROM `table_name` tn
WHERE `test_field` = "test_value";
-or-
...you could just change the name of the passed IN parameter in the stored procedure:
CREATE PROCEDURE `storedProcedureName `(
IN `sp_target_field` VARCHAR
)
...

MYSQL - Parameter being lost when using it in SQL statement

I have a stored procedure in MYSQL where I am passing one parameter which is passed into an SQL statement as you can see below however the result is returning a count of 0 where I am expecting a count of 2.
Stored Procedure:
CREATE DEFINER=`admin`#`%` PROCEDURE `EmployeesRecords`(IN employee_id varchar (1000))
BEGIN
--
declare v_count int ;
--
select count(*)
into v_count
from employees
where employees_id IN (employee_id);
--
END
One or many employee Id's can be passed into the parameter employee_id.
when Calling Stored Procedure like this : CALL EmployeesRecords('2,3'); This returns a count of 0 where I am expecting a count of 2
As for the parameter itself, I have tried various methods including changing it in the procedure to have it as "IN ('2','3') in the SQL condition however it still does not work.
However what I have noticed is that when passing one employee Id, it works successfully such as CALL EmployeesRecords('2');
Can anyone guide me to what I am doing wrong please?

Call Stored Procedure While Inserting

I am trying to insert values from one table to another one using the following insert sql query
INSERT INTO [dbo].[table2]
SELECT Exec [StoredProcedure],
[Column1]
,[Column2]
FROM [dbo].[table1]
[table2] has the following columns:
RecNo, <-- INT
Column1, <--VARCHAR(50)
Column2 <--VARCHAR(50)
[StoredProcedure] main purpose is that every time a new row to be inserted in table2 it selects the maximum value from RecNo from table2 and adds 1 to that number to create the next number (sequential).
Here is the script for the stored procedure .
GO
ALTER PROCEDURE [dbo].[UpdateRcnoNumbers]
#MaxRcno INT OUTPUT
AS
BEGIN
SELECT #MaxRcno=MAX(Recno) FROM [table2]
SELECT #MaxRcno=#MaxRcno+1
RETURN #MaxRcno
END
But I am getting an error and I am not able to call the stored procedure ? Any suggestion please .
Thank you in advance
You should write a function for this purpose , read here
The problem is, Stored Procedures don't really return output directly. They can execute select statements inside the script, but have no return value.
MySQL calls stored procedures via CALL StoredProcedureName(); And you cannot direct that output to anything, as they don't return anything (unlike a function).
Here
MySQL Call Command

How to check if a particular value exists in a variable which stores multiple value in mysql?

I am trying to create an sql trigger statement using phpmyadmin trigger interface.
Trying to do something for table 1 as shown below :
BEGIN
declare #valid_number int ;
select id into #valid_number from table 2 ;
if 10 does not exist in #valid_number then
{do something here}
end if;
END
how to achieve it?
First: a variable in a stored routine can't store multiple values, just a single one. Your statement
select id into #valid_number from table 2 ;
will only work, if the query returns exactly one row. An error will occur, if the query returns multiple rows, a warning, if the query returns no row at all, see the manual page to SELECT ... INTO:
The INTO clause can name a list of one or more variables, which can be
user-defined variables, stored procedure or function parameters, or
stored program local variables. [...]
The selected values are assigned to the variables. The number of
variables must match the number of columns. The query should return a
single row. If the query returns no rows, a warning with error code
1329 occurs (No data), and the variable values remain unchanged. If
the query returns multiple rows, error 1172 occurs (Result consisted
of more than one row).
Solution:
It's not difficult to create a statement that gives you the desired answer in exact one row, i.e.
SELECT COUNT(*) into valid_number FROM example WHERE id = 10;
This query will return 0, if the id 10 does not exists in column id and the count of occurences else. Of course there are several ways to achieve this, this is just one of them. You could rewrite your stored routine to:
BEGIN
-- prefer local variables, don't use user defined, if not needed.
DECLARE valid_number int;
SELECT COUNT(*) into valid_number FROM example WHERE id = 10;
IF valid_number = 0 THEN
-- do something here
END IF;
SELECT result;
END
Note
You could use a cursor to traverse the result of a query, but most times one wants to avoid a cursor. To use a cursor under similar conditions as of this question would not be the SQL way to do it and most times very inefficient.

Stored procedure used to insert datas in two tables

I am using a stored procedure to insert data into two tables. But when I insert the datas the total number of rows in the first table and the second table is different, so it means that sometimes it only inserted the datas in the first table but failed to insert it in the second table. But this case should not happen in my case as the Id of the two tables is related to each other. How can I solve this problem? So that when it will insert datas in both tables or no table if an error occurs so that the number of datas are the same in both the table. My stored procedure is as follows:
Begin
insert into base_table(imgPath,store,apparelType) values (imgPath,store,apparelType);
insert into data_table(cvID,color) values
(LAST_INSERT_ID(),color);
END
To make sure that the 1st query has been successfully executed, the best way would be to add an Identity column in your base_table, then proceed as follows;
DECLARE #LAST_INSERT_ID INT
DECLARE #EXECUTION_OK char(1)
SET #EXECUTION_OK = 1
insert into base_table(imgPath,store,apparelType) values (imgPath,store,apparelType)
SELECT #LAST_INSERT_ID = SCOPE_IDENTITY()
insert into data_table(cvID,color) values (#LAST_INSERT_ID, color)
GO
If exists( Select cvID from data_table where cvID= #LAST_INSERT_ID)
Begin
#EXECUTION_OK = 0
End
SCOPE_IDENTITY: Returns the last identity value inserted into an identity column in the same scope. A scope is a module: a stored procedure, trigger, function, or batch. Therefore, two statements are in the same scope if they are in the same stored procedure, function, or batch.
You can also use the mysql_affected_rows() function to verify that the query has been successful.