Get the number of affected rows in a MySQL update statement? - sql

I have stored procedure in MySQL, something like the below:
create procedure SP_Test (input1 varchar(20))
begin
update Table1 set Val1='Val' where country=input1;
//I want to see if this update changed how many rows and
//do some specific action based on this number
....
end
How can I determine how many rows were changed by this update?

Use ROW_COUNT():
SELECT ROW_COUNT();

one way, not very optimal is to simply do a select before you do the update.
select count(*) from table1 where country = 'country1'

Try the following code:
int mysql_affected_rows ([ resource $link_identifier = NULL ] )

Related

Get variables of a stored procedure from a SELECT statement

I'd like to execute a stored procedure with variables that I'm getting from a select statement like its possible in insert, update and delete.
EXEC [dbo].[upsert_release_artist_role_sp]
#release_guid = #release_guid,
#artist_id = #artist_id OUTPUT,
#external_role_id = #external_role_id
(
SELECT #release_guid, artist_id, #external_role_id
FROM #artist_ids
)
In the code, artist_id is defined in a table variable and I need a way to retrieve it.
Any idea what's the best way to tackle this?
Was solved by using https://chat.openai.com/ :D
Solved this by
DECLARE #artist_id INT
SELECT #artist_id = artist_id FROM #artist_ids
EXEC [dbo].[upsert_release_artist_role_sp]
#release_guid, #artist_id, #external_role_id
-- This has been verified in my code and works well.

How to find affected rows, after an update in SQL

I have a table and a stored procedure. I use the stored procedure to update the table. There are some cursors in the stored procedure and the SP is updating the table. I want to get the rows updated by the stored procedure. I don't want to number of updated rows, I want just updated rows.
I created a temporary table to insert with updated rows but can't get the updated rows. How can I get?
I am using SQL Server.
If your RDBMS supports it, you can use update returning like this:
sql> update your_table
set your_field = 'my new value'
where other_field = 'your condition'
returning *; -- this returning will return a result set with the modified rows
-- you could also specify a list of columns here if you don't want
-- all fields returned
Using returning clause should work with PostgreSQL, Oracle, and others.
If you are using SQLServer (as you've just stated on your question update), you can use output:
sql> update your_table
set your_field = 'my new value'
output your_list_of_fields -- this is a comma separated list of the
-- columns you want to return
where other_field = 'your condition';
You could use the INSERTED and DELETED virtual or "psuedo" tables which are created for this purpose. In UPDATE statements the virtual tables are accessible using the OUTPUT clause. Here's an example
drop table if exists #t;
go
create table #t(col_x char(1));
insert #t values('a');
update #t
set col_x='b'
output inserted.col_x as new_val,
deleted.col_x as old_val;
new_val old_val
b a

how to delete multiple records from a table (getting multiple values in input)

I want to delete multiple records from table at the same time.
Sample input:
{"INPUT":{"ID":"2200038,2200039,2200073,2200019"}}
Input will be provided from the application i.e.,
ID can be random - it gets changed based on requirements.
delete from mytable
where id = ....?
I want to delete multiple ID's coming from the input at the same time.
To delete multiple rows at once with different IDs, one approach is to use IN:
DELETE FROM mytable
WHERE ID IN (2200038,2200039,2200073,2200019)
Here's some documentation and further examples: http://www.postgresqltutorial.com/postgresql-in/
You may extract the ids from your json string as an array and delete those using ANY operator
WITH t AS
(
SELECT '{"INPUT":{"ID":"2200038,2200039,2200073,2200019"}}' AS input
)
DELETE FROM mytable
WHERE id = ANY ( SELECT unnest(
String_to_array(input::json->'INPUT'->>'ID',',')::int[])
FROM t );
Demo
Here's a demo using a Bind variable for input in psql. Note that UNNEST was not needed here.
\set input '{"INPUT":{"ID":"2200038,2200039,2200073,2200019"}}'
knayak=# DELETE FROM mytable WHERE
id = ANY( String_to_array(:'input'::json->'INPUT'->>'ID',',')::int[] )
DELETE 2
Maybe some dynamic sql will help
EXEC SQL BEGIN DECLARE SECTION;
const char *stmt = "DELETE FROM tablename WHERE ID IN(?);";
EXEC SQL END DECLARE SECTION;
EXEC SQL PREPARE mystmt FROM :stmt;
inputdata varchar; -- remove unwanted parts of the string
EXEC SQL EXECUTE mystmt USING inputdata;

How to selectively return rows inside a stored procedure on SQL Server?

I have a base stored procedure simply returning a select from the database, like this:
CREATE PROCEDURE MyProcedure
AS
BEGIN
SELECT * FROM MyTable
END
GO
But now I need to execute some logic for every row of my select. According to the result I need to return or not this row. I would have my select statement running with a cursor, checking the rule and return or not the row. Something like this:
CREATE PROCEDURE MyProcedure
AS
BEGIN
DECLARE CURSOR_MYCURSOR FOR SELECT Id, Name FROM MyTable
OPEN CURSOR_MYCURSOR
FETCH NEXT FROM CURSOR_MYCURSOR INTO #OUTPUT1, #OUTPUT2
WHILE (##FETCH_STATUS=0)
BEGIN
IF (SOME_CHECK)
SELECT #OUTPUT1, #OUTPUT2
ELSE
--WILL RETURN SOMETHING ELSE
END
END
GO
The first problem is that everytime I do SELECT #OUTPUT1, #OUTPUT2 the rows are sent back as different result sets and not in a single table as I would need.
Sure, applying some logic to a row sounds like a "FUNCTION" job. But I can't use the result of the function to filter the results being selected. That is because when my check returns false I need to select something else to replace the faulty row. So, I need to return the faulty rows so I can be aware of them and replace by some other row.
The other problem with this method is that I would need to declare quite a few variables so that I can output them through the cursor iteration. And those variables would need to follow the data types for the original table attributes and somehow not getting out of sync if something changes on the original tables.
So, what is the best approach to return a single result set based on a criteria?
Thanks in advance.
I recommend use of cursors but easy solution to your question would be to use table variable or temp table
DECLARE #MyTable TABLE
(
ColumnOne VARCHAR(20)
,ColumnTwo VARCHAR(20)
)
CREATE TABLE #MyTable
(
ColumnOne VARCHAR(20)
,ColumnTwo VARCHAR(20)
)
than inside your cursors you can insert records that match your logic
INSERT INTO #MyTable VALUES (#Output1, #Output2)
INSERT INTO #MyTable VALUES (#Output1, #Output2)
after you done with cursor just select everything from table
SELECT * FROM #MyTable
SELECT * FROM #MyTable

Sql update statement, any way of knowing what it actually did?

Typically, I test an update by running a query using the where statement and then after verifying that it does what I think I want it to copying the where clause to the update statement and executing it. But is there any way of getting the statement to return what the update did besides the '4 rows updated'
Sure, take a look at the output clause of T-SQL
http://msdn.microsoft.com/en-us/library/ms177564.aspx
You could load your records into a temp table/variable in SQL Server:
DECLARE #Temp TABLE(ID INT)
INSERT INTO #Temp (ID)
SELECT ID
FROM Customer
WHERE AcctBalance > 5000
--inspect as needed
UPDATE Customer
SET AcctBalance = 0
WHERE ID IN (SELECT ID FROM #Temp)
That depend in the server, library that you use, in php, pdo exec return number of row effected by delete or update cluase