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

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

Related

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

is insert into.. select statement transactional?

do i need to use transaction to provide all or not proposition for the following insert process?
INSERT INTO table1 ( column1 , column2)
SELECT col1, col2
FROM table2
expecting average row-count from table2 is around 150 and target database is ms sql server 2008 r2.
No, you don't need to. A single SQL statement is already in a transaction by default so there is no way that you will partually insert results or that results will be meanwhile moderated by another transaction. The fact that 2 tables are involved doesn't change the fact that a single SQL statement is used.
As your simple insert will not needed.
By default sqlserver manage this thing and at the end commit whatever you did.
If you explicitly want when multiple statement executed of insert/update or when you want to parent/child inserted in single unit of work, then you use transaction as
tran
declare #parentId int =0;
insert statement ---parent
set #parentId= ##identity
insert statement --child entry
values ( #parentId,...)
If ##ERROR > 0 then
ROLLBACK
else
COMMIT
http://www.codeproject.com/Articles/4451/SQL-Server-Transactions-and-Error-Handling
or you can use try catch block as c# in sqlserver side too.
http://msdn.microsoft.com/en-IN/library/ms175976.aspx

How to update and insert in T-SQL in one query

I have a database that needs from time to time an update.
It may also happens that there are new data while the update runs.
In MySQL there is a option
INSERT INTO IGNORE
I can't find something like this in T-SQL.
No Problem to update ID 1-4 but then there is a new record for ID 5.
The UPDATE query don't work here.
And when I try to INSERT all data again I get a DUPLICATE KEY error.
Additional Infos:
I've forgotten to say that my data come from external sources. I call an API to get data from it. From there I have to insert these data into my database.
I have to admit that I don't understand MERGE. So my solution for now is to use TRUNCATE first and then insert all data again.
Not the best solution but MERGE works, so far I understand it, with two tables. But I have only one table. And to create a table temporarly to use MERGE and later drop that table is in my eyes a bit to much for my little table with 200 records in it.
You can use MERGE keyword. Basically, you need to specify the column(s) on which to join the source of data with target table, and depending on whether it is matching (existing record) or not matching (new record), you run an UPDATE or INSERT.
Reference: http://msdn.microsoft.com/en-us/library/bb510625.aspx
Is a stored procedure an option?
CREATE PROCEDURE dbo.Testing (#ID int, #Field1 varchar(20))
AS
BEGIN
UPDATE tblTesting
SET Field1 = #Field1
WHERE ID = #ID
IF ##ROWCOUNT = 0
INSERT INTO tblTesting (ID, Field1) SELECT #ID, #Field1
END

getting number of records updated or inserted in sql server stored procedure

I have an SP that inserts some records and updates others and deletes some. What I want is to return the count values of what was inserted and what was updated and what was deleted. I thought I could use ##ROWCOUNT but that is always giving me a 1.
After my INSERT I run:
PRINT ##ROWCOUNT
But my message console shows what really happened and this number:
(36 row(s) affected)
1
So I can see that 36 records were actually updated but ##ROWCOUNT returned a 1.
I am trying to do the same thing after the UPDATE and DELETE parts of the SP runs with the same result.
##ROWCOUNT will show the number of rows affected by the most recent statement - if you have any statements between the INSERT and the PRINT then it will give you the wrong number.
Can you show us a little more code so we can see the order of execution?
Depending on how #ninesided's answer works for you, you could also use the output clause on each update/insert/delete and get the counts from there.
Example:
declare #count table
(
id int
)
update mytable
set oldVal = newVal
output inserted.field1 into #count
select count(*) from #count
You could reuse the count table throughout, and set variables as needed to hold the values.

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

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 ] )