Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return all primary keys affected by update query

Is it possible to retrieve all the primary keys affected by an update query? Ex:

Table:

+-------------+---------+--------+
|idx (PK, int)|FirstName|LastName|
+-------------+---------+--------+
|1            |Jane     |Smith   |
+-------------+---------+--------+
|2            |John     |Test    |
+-------------+---------+--------+
|3            |Adam     |Smith   |
+-------------+---------+--------+

Query:

UPDATE clients SET [LastName] = 'Smith' WHERE [FirstName] = 'John'

What i want returned:

2

But i also want this method to work for multiple rows... Ex:

Query:

UPDATE clients SET [FirstName] = 'test' WHERE [LastName] = 'Smith'

What i want returned:

1, 3

like image 269
Adam Nygate Avatar asked Jan 15 '14 00:01

Adam Nygate


People also ask

What is the return value of update query?

"The update() method is applied instantly and returns the number of rows affected by the query." The actual return value depends on the database backend. MySQL, for example, will always return 1 if the query is successful, regardless of the number of affected rows.

Can you update primary key SQL?

You can modify a primary key in SQL Server by using SQL Server Management Studio or Transact-SQL. You can modify the primary key of a table by changing the column order, index name, clustered option, or fill factor.

How can you guarantee that one row will be returned from a query?

You can use the FETCH FIRST 1 ROW ONLY clause in a SELECT statement to ensure that only one row is returned. This action prevents undefined and unpredictable data from being returned when you specify the INTO clause of the SELECT statement.

What happens if there are 2 primary keys?

A table can have only one primary key, which may consist of single or multiple fields. When multiple fields are used as a primary key, they are called a composite key. If a table has a primary key defined on any field(s), then you cannot have two records having the same value of that field(s).


2 Answers

Use the OUTPUT clause in conjunction with a table variable to get all IDs updated:

declare @insertedIds table (id int)

update
  supportContacts
set
  type = 'Email, updated'
output inserted.id into @insertedIds
where
  type = 'Email'

select id from @insertedIds
like image 58
Joe Rinehart Avatar answered Oct 16 '22 20:10

Joe Rinehart


Create a transaction that:

  1. selects your records into a temp table
  2. updates the main table
  3. selects from the temp table
like image 39
Dan Bracuk Avatar answered Oct 16 '22 21:10

Dan Bracuk