Reputation: 25
I'm new to SQL and I want to know the approach to solve this small problem
Select * from ApplicationData where ApplicationId = @AppID
AppID can be null as well as it could contain some value. When null value is received, it return all the application. Is there any way we can alter Where clause.
Example
Select * from ApplicationData where Case When <some condition> then
ApplicationId = @AppID else ApplicationId is null;
Thanks
Upvotes: 1
Views: 654
Reputation: 272106
This should work:
SELECT * FROM ApplicationData
WHERE (ApplicationId IS NULL AND @AppID IS NULL) OR ApplicationId = @AppID
This is an alternate approach:
SELECT * FROM ApplicationData
WHERE ISNULL(ApplicationId, -1) = ISNULL(@AppID, -1)
Upvotes: 1
Reputation: 25351
Try this:
SELECT *
FROM ApplicationData
WHERE CASE WHEN @AppID IS NULL THEN ApplicationId IS NULL
ELSE ApplicationId = @AppID END;
Alternatively, you can split it into two conditions like this:
SELECT *
FROM ApplicationData
WHERE ApplicationId = @AppID
OR (ApplicationId IS NULL AND @AppID IS NULL);
Upvotes: 0
Reputation: 3591
For your case you should do like this
IF @AppID IS NULL
BEGIN
SELECT * FROM ApplicationData WHERE ApplicationId is null
END
ELSE
BEGIN
SELECT * FROM ApplicationData WHERE ApplicationId = @AppID
END
Upvotes: 0
Reputation: 610
always check your parameter first before put into consideration, remember, the bracket is very important, especially for multiple parameters
--Example For Single parameter
Select * from ApplicationData where (@AppID IS NULL OR ApplicationId = @AppID)
--Example for multiple parameter(s)
Select * from ApplicationData
where (@AppID IS NULL OR ApplicationId = @AppID)
OR (@AnotherAppID IS NULL OR AnotherApplicationId = @AnotherAppID )
make sure that u have covered your parameter(s), then your query will work fine, cheer =)
Upvotes: 0
Reputation: 485
If you're doing this in a stored procedure then use logic to switch between the two filter requirements. However this will only give you optimal code if the ApplicationId column is included, preferably as the first key, in an index.
IF @AppID IS NULL
BEGIN
SELECT * FROM ApplicationData
END
ELSE
BEGIN
SELECT * FROM ApplicationData WHERE ApplicationId = @AppID
END
Why is this the best solution? Because the SQL engine will create two query plans for this stored procedure. The query plans will give you the optimal solution for the two filtering requirements. As they are small statements and you only require two possible outcomes you're not creating any burden on the query cache and your code is very readable. If your requirements were more complex, with many variation of filtering then you should consider Dynamic SQL.
If you are not using stored procedures then your application layer should dynamically create the two separate query strings.
There has been many articles written on this subject. I could dig out a few good ones for you if you need.
Upvotes: 2