从数据库中选择具有2列的单行可能包含数据或可以为null

时间:2015-04-15 07:22:59

标签: sql sql-server

declare @bsLineCode int=4

select * from table where 
(BusinessLineCodeIDT  = @bsLineCode OR BusinessLineCodeIDT IS NULL)

它给了我两行

IDT BusinessLineCodeIDT  
0   NULL
0   98

但我希望当BusinessLineCodeIDT具有值时,则选择第2行。

2 个答案:

答案 0 :(得分:2)

你可以这样做。

SELECT TOP 1 *
FROM table
WHERE BusinessLineCodeIDT = @bsLineCode OR BusinessLineCodeIDT IS NULL
ORDER BY CASE WHEN BusinessLineCodeIDT IS NULL THEN 1 ELSE 0 END

答案 1 :(得分:0)

你确定你的where子句是否正确?您是否想要相同的行代码 OR 业务行代码idt为null? 你可以这样做:

    select TOP 1 * from table where 
    (BusinessLineCodeIDT  = @bsLineCode OR BusinessLineCodeIDT IS NULL) 
    ORDER BY BusinessLineCodeIDT Desc