如何根据条件选择列?

时间:2009-09-02 15:50:38

标签: sql sql-server tsql

我有一个名为@status的变量,我在这个select语句之前设置了它:

Select
ordr_num as num,
ordr_date as date,
ordr_ship_with as shipwith
From
order
where ordr_num = @ordrNum

我只想选择ordr_ship_with@status <> 'Cancelled',否则我想为shipwith选择null。我该如何做到这一点?

5 个答案:

答案 0 :(得分:34)

SELECT ordr_num as num, ordr_date as date, 
    CASE WHEN @status<>'Cancelled' THEN ordr_ship_with ELSE NULL END as shipwith 
FROM order 
WHERE ordr_num = @ordrNum

答案 1 :(得分:4)

试试这个

Select 
    ordr_num as num, 
    ordr_date as date, 
    CASE 
        WHEN @Status <> 'Cancelled' THEN ordr_ship_with 
        ELSE NULL END
    as shipwith 
From order 
where ordr_num = @ordrNum

虽然我觉得STATUS是Order表中的实际列。在这种情况下,请执行以下操作:

Select 
    ordr_num as num, 
    ordr_date as date, 
    CASE 
        WHEN Status <> 'Cancelled' THEN ordr_ship_with 
        ELSE NULL END
    as shipwith 
From order 
where ordr_num = @ordrNum

答案 2 :(得分:2)

Select
    ordr_num as num,
    ordr_date as date,
    CASE WHEN @status <> 'Cancelled' THEN ordr_ship_with ELSE NULL END as shipwith
From
    order where ordr_num = @ordrNum

答案 3 :(得分:1)

答案 4 :(得分:0)

试试这个

SELECT CASE     
 WHEN @status <> 'cancelled' THEN ordr_ship_with  
 ELSE null  
END AS shipwith, ... other fields