SQL在where子句中使用CASE

时间:2018-09-04 08:11:21

标签: sql-server tsql case

以下是表格的示例:

     acIdent   |  acSubject          | acCode
     200.2.013 |                     | F-202
     200.2.013 | Minsk traktor works | F202.GRS

这是我尝试做的事情:

     declare @subj varchar(30)

     set @subj = 'Minsk traktor works'

     select acIdent, acSubject, acCode
     from tHE_SetItemExtItemSubj where acIdent = '200.2.013' and
     acSubject = (
            case 
            when @subj = acSubject then @subj
            else '' end
         )

我的目标是只获得一张记录。我的示例返回两个记录。 如果表中存在@subj,则返回acCode-F202.GRS,否则返回F-202。

帮助请

4 个答案:

答案 0 :(得分:3)

如果我对您的理解正确,那么您正在寻找以下内容:

 declare @subj varchar(30)

 set @subj = 'Minsk traktor works'

 select top(1) acIdent, acSubject, acCode
 from tHE_SetItemExtItemSubj 
 where acIdent = '200.2.013' 
   and (acSubject = @subj or acSubject = '')
 order by len(acSubject) desc

答案 1 :(得分:1)

我已经像上面这样编译了您的查询:

declare @MyTable as table
    (   ID  int identity primary key
    ,   acIdent     varchar(100)
    ,   acSubject   varchar(200)
    ,   acCode      varchar(100)
    )

insert into @MyTable
    (   acIdent
    ,   acSubject
    ,   acCode  )
    values
    (   '200.2.013'
    ,   ''
    ,   'F-202' ),
    (   '200.2.013'
    ,   'Minsk traktor works'
    ,   'F-202' )

declare @subj varchar(30)

    set @subj = 'Minsk traktor works'

    select
        acIdent
    ,   acSubject
    ,   acCode
    ,   case acSubject when  @subj then @subj else '' end
    from @MyTable where acIdent = '200.2.013'
    and  acSubject = (case when acSubject = @subj then @subj else '' end)

    select
        acIdent
    ,   acSubject
    ,   acCode
    ,   case acSubject when  @subj then @subj else '' end
    from @MyTable where acIdent = '200.2.013'
    and  acSubject = @subj

在这2个查询中,您会注意到第一个查询将始终为您提供2行,因为您的代码存在缺陷。

您将注意到的第二个查询只会给您一条记录。

结果将如下所示:

Results

答案 2 :(得分:1)

这将无济于事,因为您只需要使用一种条件就可以获得一条记录。如果只需要检查单个条件,为什么要用例呢?

declare @subj varchar(30)
set @subj = 'Minsk traktor works'
select top(1) acIdent, acSubject, acCode
from tHE_SetItemExtItemSubj 
where acIdent = '200.2.013' 
and (acSubject = @subj)

答案 3 :(得分:0)

使用case函数可以执行以下操作:

 -- assumes @subj is not '' nor null. 
 select y.acIdent, y.acSubject, y.acCode
 from tHE_SetItemExtItemSubj y
 where y.acIdent = '200.2.013' 
   and y.acSubject = 
   (case 
    when exists(select * from  tHE_SetItemExtItemSubj x where 
                x.acIdent = y.acIdent and x.acSubject = @subj) 
    then @subj else '' 
    end)

案例函数也可以嵌套。这是一个具有与上述功能相同的示例(在这种情况下,这可能有些矫kill过正,但是当您做更复杂的事情时,该技术可能会很有用):

 -- assumes @subj is not '' nor null. 
 select y.acIdent, y.acSubject, y.acCode
 from tHE_SetItemExtItemSubj y
 where y.acIdent = '200.2.013' 
   and 1 = 
   (case 
    when exists(select * from  tHE_SetItemExtItemSubj x where 
                x.acIdent = y.acIdent and x.acSubject = @subj) 
    then 
        case when y.acSubject = @subj then 1 else 0 end
    else 
        case when y.acSubject = '' then 1 else 0 end
    end)