这是一个表的例子:
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。
请帮忙
如果我理解正确,你正在寻找这样的东西:
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
我在上面编译了你的查询,如下所示:
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行,因为您的代码存在缺陷。
您将注意到的第二个查询只会给您一条记录。
结果将如下所示:
这不会有用,因为你必须只使用一个条件获得一条记录。如果您必须仅针对单一条件进行检查,为什么要使用案例?
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)
通过案例功能可以做到这样的事情:
-- 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)
案例函数也可以嵌套。这是一个具有与上面相同功能的例子(在这种情况下它可能有点过分,但是当你做更复杂的事情时,这个技术会很有用):
-- 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)