When you need Dynamic WHERE Clause I can use;
CREATE PROCEDURE [dbo].[sp_sel_Articles]
@articleId INT = NULL
, @title NVARCHAR(250) = NULL
, @accessLevelId INT = NULL
AS
BEGIN
SELECT *
FROM table_Articles Art
WHERE
(Art.ArticleId = @articleId OR @articleId IS NULL)
AND (Art.Title LIKE '%' + @title + '%' OR @title IS NULL)
AND (Art.AccessLevelId = @accessLevelId OR @accessLevelId IS NULL)
END
So, I am able to invoke this procedure -for example- ONLY by ArticleId
EXEC [sp_sel_Articles] @articleId = 3
But, sometimes I’ll need to invoke by AccessLevelId and sometimes NOT by an EXACT VALUE. For example, I’ll need MORE THAN the given accesslevelId or LESS THAN.
Current procedure can ONLY handle the EXACT value by using
Art.AccessLevelId = @accessLevelId
Could also be possible to give the CONDITION type as well as the value into the procedure? It may seem very odd in this example but please just bear with me:
CREATE PROCEDURE [dbo].[sp_sel_Articles]
@articleId INT = NULL
, @title NVARCHAR(250) = NULL
, @accessLevelId INT = NULL
, **@accessLevelIdCondition**
AS
BEGIN
SELECT *
FROM table_Articles Art
WHERE
(Art.ArticleId = @articleId OR @articleId IS NULL)
AND (Art.Title LIKE '%' + @title + '%' OR @title IS NULL)
AND (Art.AccessLevelId **@accessLevelIdCondition** @accessLevelId OR @accessLevelId IS NULL)
END
Perhaps an Function can be used, I don’t know. Since, there will be at least 20 Procedure that will require this flexibility, I’ll need a better, more global solution as much as possible rather than writing IF ELSE condition in every procedure.
Thanks in advance,
Read this http://www.sommarskog.se/dynamic_sql.html before applying