---
title: "Transaction with multiple updates and unique index"  
description: "Transaction with multiple updates and unique index"  
author: "Sandra Emily"  
published: 2023-07-30  
updated: 2023-07-31  
canonical: https://www.mindstick.com/forum/159374/transaction-with-multiple-updates-and-unique-index  
category: "mssql server"  
tags: ["mssql server", "sql server", "sql"]  
reading_time: 2 minutes  

---

# Transaction with multiple updates and unique index

[Transaction](https://www.mindstick.com/blog/175/transactions-in-database) with [multiple](https://www.mindstick.com/blog/12797/iowa-is-expected-to-see-heavy-growth-in-multiple-sectors) [updates](https://yourviews.mindstick.com/view/85235/global-efforts-to-combat-climate-change-updates-and-initiatives) and [unique index](https://www.mindstick.com/forum/158048/with-sql-server-i-want-a-unique-index-on-only-the-non-null-values)

## Replies

### Reply by Aryan Kumar

Sure, here is an example of a transaction with multiple updates and a [unique](https://www.mindstick.com/blog/12870/how-to-be-unique-in-business) [index](https://www.mindstick.com/blog/198/index-in-sql-server):

SQL

```plaintext
BEGIN TRANSACTION;

UPDATE Customers
SET FirstName = 'John',
LastName = 'Doe'
WHERE CustomerID = 1;

UPDATE Customers
SET FirstName = 'Jane',
LastName = 'Doe'
WHERE CustomerID = 2;

-- Check for unique constraint violation
IF EXISTS (
SELECT 1
FROM Customers
WHERE FirstName = 'Jane'
AND LastName = 'Doe'
)
BEGIN
ROLLBACK TRANSACTION;
END;

COMMIT TRANSACTION;
```

This transaction will update the `Customers` table to change the first and last names of the customers with the IDs 1 and 2. However, it will first check to see if there is already a customer with the first name `Jane` and the last name `Doe`. If there is, the transaction will roll back, meaning that the updates will not be made.

The `BEGIN TRANSACTION` statement starts the transaction. The `UPDATE` statements update the `Customers` table. The `IF EXISTS` statement checks for a unique constraint violation. The `ROLLBACK TRANSACTION` statement rolls back the transaction if there is a unique constraint violation. The `COMMIT TRANSACTION` statement commits the transaction.

This code is not complete, as it does not handle errors that could occur during the transaction. However, it provides a basic example of how to perform a transaction with multiple updates and a unique index.


---

Original Source: https://www.mindstick.com/forum/159374/transaction-with-multiple-updates-and-unique-index

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
