I am using MSSQL 2005 Server and I have the following SQL query.
IF @CategoryId IN (1,2,3)
BEGIN
INSERT INTO @search_temp_table
SELECT * FROM (SELECT d.DataId, (SELECT [Name] FROM Category WHERE CategoryId = d.CategoryId) AS 'Category', d.Description, d.CompanyName, d.City, d.CategoryId,
d.CreatedOn, d.Rank, d.voteCount, d.commentCount, d.viewCount
FROM Data d
INNER JOIN Keyword k
ON d.DataId = k.DataId
WHERE FREETEXT(k.Keyword, @SearchQ) AND d.CategoryId=@CategoryId AND d.IsSearch=1 AND d.IsApproved=1 ) AS Search_Data
END
ELSE
BEGIN
INSERT INTO @search_temp_table
SELECT * FROM (SELECT d.DataId, (SELECT [Name] FROM Category WHERE CategoryId = d.CategoryId) AS 'Category', d.Description, d.CompanyName, d.City, d.CategoryId,
d.CreatedOn, d.Rank, d.voteCount, d.commentCount, d.viewCount
FROM Data d
INNER JOIN Keyword k
ON d.DataId = k.DataId
WHERE FREETEXT(k.Keyword, @SearchQ) AND d.IsSearch=1 AND d.IsApproved=1 ) AS Search_Data
END
In the above query I have the category condition,
d.CategoryId=@CategoryId
which is executed when any category is passed, if no category is passed then I am not considering category condition in where clause, To implement category condition only when if the category in (1,2,3) I have used If-Clause, but can't we do this in single where query?? that means just check if the values is there in the category (or if it's easy then we can only check for 1,2,3 values) then that condition will be applied else query will not consider the category condition.
Is there any way, using CASE, or NOT NULL statements ??