Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

Update with CASE and multiple WHEN conditions executing only one condition

$
0
0

I have a temporary table named SheetData. When an Excel sheet data is passed as XML to a stored procedure, the data is stored in this SheetData table.

There is no reason to have Primary Key and other constraints in this table because SheetData can have any column as NULL and can have duplicates.

Below are the scripts:

CREATE TABLE #SheetData
(
	User_ID	int,
	GlobalSales_ID	int,
	Sales_ID	int,
	Country_ID	int,
	Location_ID		int,
	Error_Desc	varchar(500)
)

INSERT INTO SheetData(User_ID, GlobalSales_ID, Sales_ID, Country_ID, Location_ID) VALUES (1, 3, null, 4, null)

INSERT INTO SheetData(User_ID, GlobalSales_ID, Sales_ID, Country_ID, Location_ID) VALUES (null, null, 1, 4, 3)

INSERT INTO SheetData(User_ID, GlobalSales_ID, Sales_ID, Country_ID, Location_ID) VALUES (2, 4, 3, null, null)

I want to perform UPDATE on this table to fill a valid error description in the column: Error_Desc. I attempted this UPDATE statement:

UPDATE SheetData 
	SET Error_Desc = 
		CASE
			WHEN User_Id IS NULL THEN 'User not found'
			WHEN GlobalSales_Id IS NULL THEN ISNULL(Error_Desc,'') + ' Global Sales details not found'
			WHEN Sales_Id IS NULL THEN ISNULL(Error_Desc,'') + ' Sales details not found'
			WHEN Country_Id IS NULL THEN ISNULL(Error_Desc,'') + ' Country not found'
			WHEN Location_Id IS NULL THEN ISNULL(Error_Desc,'') + ' Location not found'
		END
The problem with this statement is that it is updating only error description of first encountered condition. It is skipping other conditions.

For example, if Country_ID and Location_ID are both null, I want error description as: Country not found, Location not found.

But what it actually gives is: Country not found. It skips other conditions. I want it to keep concatenating each condition.



Viewing all articles
Browse latest Browse all 23857

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>