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 S.SoftNo > 0 ELSE S.SoftNo = @SoftNo)
如果Version等于零,我想列出所有版本号大于0但如果不等于0,那么Version应该是它的值。
SoftNo也是如此。
如何修复SQL查询。它只是不起作用。
更多详情:
这就是我想要实现的目标:
if(Version == 0)
{
display every single rows if their version number is greater then 0;
}
else
{
Lets assume that Version is equal to 5. Then just display the rows if their Version number is equal to 5;
} // This is like a C# code of what I am trying to do in my sql query.
答案 0 :(得分:1)
您必须使用CASE WHEN语句而不是if
答案 1 :(得分:1)
尝试这样的事情:
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))
答案 2 :(得分:1)
您是否考虑过使用SQL案例?
SELECT col1, col2,
CASE
WHEN expression THEN return
WHEN expression THEN return
ELSE return
END AS NameOfNewColWithReturnValues
FROM Col_FROM_WHICH_TABLE
答案 3 :(得分:0)
不太明白,但如果你的意思是输入变量等于零,你可以这样做:
SELECT S.Id, S.Name, S.Version, S.SoftNo
FROM SOFTWARE S WITH(NOLOCK)
WHERE ((@Version = 0 AND S.Version > 0) OR (S.Version = @Version AND @Version > 0))
AND (@SoftNo = 0 AND S.SoftNo > 0) OR (@SoftNo = S.SoftNo AND @SoftNo > 0 )
答案 4 :(得分:0)
相反,我想出了这个解决方法,
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";
}
结论,如果将其他部分移至代码端。
答案 5 :(得分:0)
为什么不
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))
)
(你真的需要NOLOCK吗?)
答案 6 :(得分:0)
不要使用连接的SQL,这是一种不良习惯,增加了SQL注入漏洞的可能性。您的SQL代码现在与以下(更安全)代码完全相同:
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)