SELECT S.Id, S.Name, S.Version, S.SoftNo
FROM SOFTWARE S WITH(NOLOCK)
WHERE (IF S.Version = 0 THEN S.Version > 0 ELSE S.Version = @Version)
AND (IF S.SoftNo = 0 THEN
You have to use CASE WHEN statement instead of if
Have you thought of using SQL cases?
SELECT col1, col2,
CASE
WHEN expression THEN return
WHEN expression THEN return
ELSE return
END AS NameOfNewColWithReturnValues
FROM Col_FROM_WHICH_TABLE
Try something like this:
SELECT S.Id, S.Name, S.Version, S.SoftNo
FROM SOFTWARE S WITH(NOLOCK)
WHERE ((@Version = 0 AND S.Version > 0) OR
(@Version <> 0 AND S.Version = @Version)) AND
((@SoftNo = 0 AND S.SoftNo > 0) OR
(@SoftNo <> 0 AND S.SoftNo = @SoftNo))
Don't use concatenated SQL, it is a poor habit that increases the probability of SQL injection vulnerabilities. Your SQL code is now the exact same as the following (safer) code:
SELECT
S.Id, S.Name, S.Version, S.SoftNo
FROM
SOFTWARE S WITH(NOLOCK)
WHERE
(@Version = 0 OR @Version = S.Version)
AND (@SoftNo = 0 OR @SoftNo = S.SoftNo)
Why not do
SELECT S.Id, S.Name, S.Version, S.SoftNo
FROM SOFTWARE S WITH(NOLOCK)
WHERE
(
(@Version = 0 OR (@Version <> 0 AND S.Version = @Version))
AND
(@SoftNo = 0 OR (@SoftNo <> 0 AND S.SoftNo = @SoftNo))
)
(Do you really need the NOLOCK?)
Instead, I came up with this workaround,
sSQL = @"SELECT S.Id, S.Name, S.Version, S.SoftNo
FROM SOFTWARE S WITH(NOLOCK)
WHERE 1 = 1";
// 1=1 is used just to list everything.
if(pVersion != 0)
{
sSQL += " AND S.Version = @Version";
}
if(pSoftNo != 0)
{
sSQL += " AND S.SoftNo = @SoftNo";
}
Conclusion, if else part is moved to code side.