how can i write the select case statement in t-sql ? My Code below doesn’t work, help
I just want the match case, insert statement start insert the value into table.
SET @DayName = dbo.GetWeekDayNameOfDate(@SaleDate)
SELECT
CASE @DayName
WHEN 'Sunday' THEN
INSERT INTO Tmp_Data(ProductID,ProductName,Sunday,NetProfit)
VALUES(@ProductId,@ProductName,@Qty,@Profit);
WHEN 'Monday' THEN
INSERT INTO Tmp_Data(ProductID,ProductName,Monday,NetProfit)
VALUES(@ProductId,@ProductName,@Qty,@Profit);
WHEN 'Tuesday' THEN
INSERT INTO Tmp_Data(ProductID,ProductName,Tuesday,NetProfit)
VALUES(@ProductId,@ProductName,@Qty,@Profit);
WHEN 'Wednesday' THEN
INSERT INTO Tmp_Data(ProductID,ProductName,Wednesday,NetProfit)
VALUES(@ProductId,@ProductName,@Qty,@Profit);
WHEN 'Thursday' THEN
INSERT INTO Tmp_Data(ProductID,ProductName,Thursday,NetProfit)
VALUES(@ProductId,@ProductName,@Qty,@Profit);
WHEN 'Friday' THEN
INSERT INTO Tmp_Data(ProductID,ProductName,Friday,NetProfit)
VALUES(@ProductId,@ProductName,@Qty,@Profit);
WHEN 'Saturday' THEN
INSERT INTO Tmp_Data(ProductID,ProductName,Saturday,NetProfit)
VALUES(@ProductId,@ProductName,@Qty,@Profit);
END
I agree with @John Dewey’s comment – you shouldn’t have a column for each weekday, but rather a single column that has the weekday. Assuming for a moment that you can’t fix the broken schema, next you need to understand that
CASEis an expression that returns a value, not a control of flow statement like it works in some other languages. This means you can’t sayCASE THEN something THEN go do something else.Here is one way to write your statement that will reduce at least some of the redundancy you’re attempting:
You could also also build the statement in dynamic SQL. Not the way I would prefer, just including that option for brevity.