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
"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.
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.
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.
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).
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
Create a transaction that:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With