IF ELSE Statement in SQL

后端 未结 7 505
名媛妹妹
名媛妹妹 2021-01-22 12:10
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          


        
相关标签:
7条回答
  • 2021-01-22 12:40

    You have to use CASE WHEN statement instead of if

    0 讨论(0)
  • 2021-01-22 12:41

    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 
    
    0 讨论(0)
  • 2021-01-22 12:42

    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))
    
    0 讨论(0)
  • 2021-01-22 12:51

    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)
    
    0 讨论(0)
  • 2021-01-22 12:54

    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?)

    0 讨论(0)
  • 2021-01-22 12:56

    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.

    0 讨论(0)
提交回复
热议问题