Using If else in SQL Select statement

后端 未结 11 1613
感情败类
感情败类 2020-12-24 05:35

I have a select statement which will return 2 columns.

ID | IDParent

Then in my program I have to test if IDParent is < 1 then use

相关标签:
11条回答
  • 2020-12-24 05:48

    you can use CASE

    SELECT   ...,
             CASE WHEN IDParent < 1 THEN ID ELSE IDPArent END AS ColumnName,
             ...
    FROM     tableName
    
    0 讨论(0)
  • 2020-12-24 05:48

    You can also use a union construct. I'm not sure if CASE is a common SQL construct ...

    SELECT ID FROM tabName WHERE IDParent<1 OR IDParent IS NULL
    UNION 
    SELECT IDParent FROM tabName WHERE IDParent>1
    
    0 讨论(0)
  • 2020-12-24 05:49

    You can use simply if statement under select query as like I have described below

    if(some_condition,if_satisfied,not_satisfied)

    SELECT IF(IDParent < 1,ID,IDParent)  FROM yourTable ;
    
    0 讨论(0)
  • 2020-12-24 05:53

    Here, using CASE Statement and find result:

    select (case when condition1 then result1
                 when condition2 then result2
                 else result3
                 end) as columnname from tablenmae:
    

    For example:

    select (CASE WHEN IDParent< 1 then ID 
                 else IDParent END) as columnname
    from tablenmae
    
    0 讨论(0)
  • 2020-12-24 05:53

    The query will be like follows

    SELECT (CASE WHEN tuLieuSo is null or tuLieuSo=''
                THEN 'Chưa có đĩa' 
                ELSE 'Có đĩa' End) AS tuLieuSo,moTa
    FROM [gPlan_datav3_SQHKTHN].[dbo].[gPlan_HoSo]
    
    0 讨论(0)
  • 2020-12-24 05:56

    I Have a Query With This result :

    SELECT Top 3
     id,
     Paytype
     FROM dbo.OrderExpresses
     WHERE CreateDate > '2018-04-08'
    

    The Result is :

    22082   1
    22083   2
    22084   1
    

    I Want Change The Code To String In Query, So I Use This Code :

    SELECT TOP 3
     id,
     CASE WHEN Paytype = 1 THEN N'Credit' ELSE N'Cash' END AS PayTypeString
     FROM dbo.OrderExpresses
     WHERE CreateDate > '2018-04-08'
    

    And Result Is :)

    22082   Credit
    22083   Cash
    22084   Credit
    
    0 讨论(0)
提交回复
热议问题