What is the best practice/approach to writing a SP that returns either a single row or all rows based on the 1 parameter passed in?
Lately we've noticed a need to retrieve either 1 record or all records from tables within our DB (Customer(s), Location(s), Room(s), etc.). So for customers, we would have 2 SP's:
And
We were thinking of combining them into 1 and making the parameter NULL by default, then checking for it:
The only issue I see with this is if you had a large table and were listing out the fields, there would be the potential for not having the same fields in both SELECT statements.....but other than Dynamic SQL, is there a better way/approach?
Lately we've noticed a need to retrieve either 1 record or all records from tables within our DB (Customer(s), Location(s), Room(s), etc.). So for customers, we would have 2 SP's:
Code:
SELECT *
FROM Customers
And
Code:
SELECT *
FROM Customers
WHERE CustomerID = @CustomerID
We were thinking of combining them into 1 and making the parameter NULL by default, then checking for it:
Code:
IF @CustomerID IS NULL
SELECT *
FROM Customers
ELSE
SELECT *
FROM Customers
WHERE CustomerID = @CustomerID
The only issue I see with this is if you had a large table and were listing out the fields, there would be the potential for not having the same fields in both SELECT statements.....but other than Dynamic SQL, is there a better way/approach?