I am trying to decide whether to set up multiple queries specifically for different order by situations or to use an Order By.
How would I change the following to use one query with an Order By (without using dynamic SQL) and CASE Statement?
And if you can would that be better?
Thanks,
Tom
How would I change the following to use one query with an Order By (without using dynamic SQL) and CASE Statement?
And if you can would that be better?
Code:
If OBJECT_ID('tempdb..#Stage') IS NOT NULL
DROP TABLE #Stage
CREATE TABLE #Stage
(
StageID int,
ShipNumber varchar(10),
PONumber varchar(10),
iQty int
)
DECLARE @OrderBy int
SELECT @OrderBy = 3
INSERT #Stage (StageID, ShipNumber, PONumber, iQty) VALUES (20, 'MZ12345', 'A4735', 10)
INSERT #Stage (StageID, ShipNumber, PONumber, iQty) VALUES (22, 'MZ12345', 'A4735', 25)
INSERT #Stage (StageID, ShipNumber, PONumber, iQty) VALUES (23, 'MZ12345', 'A4735', 10)
INSERT #Stage (StageID, ShipNumber, PONumber, iQty) VALUES (35, 'MZ12345', 'J3321', 40)
INSERT #Stage (StageID, ShipNumber, PONumber, iQty) VALUES (36, 'MZ12345', 'J3321', 25)
INSERT #Stage (StageID, ShipNumber, PONumber, iQty) VALUES (32, 'MZ12345', 'V3199', 10)
IF @OrderBy = 1
BEGIN
SELECT * FROM #Stage
ORDER BY ShipNumber
END
IF @OrderBy = 2
BEGIN
SELECT * FROM #Stage
ORDER BY PONumber, ShipNumber, iQty
END
IF @OrderBy = 3
BEGIN
SELECT * FROM #Stage
ORDER BY iQty, PONumber
END
Thanks,
Tom