Estimated reading time: 3 minutes
In this blog post we will look at how to update database records, and also where you try to apply updates and they cannot be completed.
It will be updating the records below:
Updating a single record
--Update one record on its own UPDATE dbo.CUSTOMER SET customer_type = 'WEB' WHERE CUSTOMER_NO = 125872;
Running the above code gives this output, resulting in the value been updated per our SQL statement.
Updating multiple rows at once
There maybe scenarios where you want to have multiple records/rows updated at once, the below code will provide you with an example of how this can be achevied:
--Update multiple rows at once UPDATE dbo.CUSTOMER SET customer_type = 'WEB' WHERE CUSTOMER_NO in(333333,456789)
This will now give you updated values in the output below. It is a very handy way to at once get multiple records updated.
Show an update that is valid but will not change anything
--Show an update request that does not complete UPDATE dbo.CUSTOMER SET CUSTOMER_NO = 2,customer_type = 'ERROR' WHERE CUSTOMER_NO = 456789222 ---> will not execute as this value does not exist, it ignores.
With the above code, we have a valid update statement. In this scenario it will not complete as the CUSTOMER_NO does not exist on the database table.
In essence the output is exactly the same as in the previous example.
Update multiple column values
In our final example here, we are going to show how to update the CUSTOMER_No and the customer_type values.
The below SQL will change both values, but it is important to note that as the CUSTOMER_NO is a primary key, it cannot be changed to a number that already exists as primary keys can’t be null or have duplicates.
UPDATE dbo.CUSTOMER SET CUSTOMER_NO = 3,customer_type = 'ERROR' WHERE CUSTOMER_NO = 333333
So to wrap up there are a number of ways to update your database table. Here we have introduced some examples. There are also some additional steps you could take:
- Count all the records before and after to ensure they remain the same.
- Create a copy of the table before updates are applied, and then compare that to the updated table. The differences should be what you expect to see.