Laziale Laziale - 4 months ago 10
SQL Question

sql update field in the table only if the field is null

I have this SP:

ALTER PROCEDURE [dbo].[UpdateContractInfo](@UserGroupId int, @Quantity int, @ContractName varchar(150))
AS
BEGIN

UPDATE [contract]
SET totalUsers = @Quantity, contractName = @ContractName
WHERE userGroupId = @UserGroupId
END


I want to enhance that query a bit to check first the contractName column.
If the column is null then proceed with update of contractName otherwise skip the update of that field.
totalUsers field should be updated one way or another.

Thanks

Answer

use CASE STATEMENT

Try This

UPDATE [contract]
SET totalUsers = @Quantity, 
contractName = CASE WHEN contractName IS NULL THEN @ContractName ELSE contractName END
WHERE userGroupId = @UserGroupId