我是SQL Server 2005存储过程的初学者。我似乎无法按要求工作。如何根据SQL Server 2005中的条件返回一组值?
我有一个sp从一个名为annot
的表中获取参数@caseid。 @caseid
被分配到列src_caseid
的值,并且可以在表annot
中有多个参考(ref_caseid
)或没有。我想设置一个条件并根据表case
中的列court
设置适当的shepardsflag,我使用INNER JOIN。
基本上,这是该方案:
- 表
annot
-ref_caseid, src_caseid, annotation
- 表
case
-caseid, court
组从内的结果的实施例JOIN上ref_caseid = caseid
这样的:
ref_caseid src_caseid annotation court
17334 17338 Refd high court
17600 17338 Foll federal court
18271 17338 Foll federal court
43220 17338 Not Foll supreme court
需要设置的条件:
从记录集中,如果存在federal court
,则只应该执行federal court
行。如果发现没有federal court
,那么它会将其他案件与其他法院值进行比较。
为了达到这个目的,我为federal court
计数设置了一个计数器。但似乎SQL只读取最后一行并基于它设置@courtFC
值。我试过order by
,但似乎没有工作。
从上面的示例中,case 17338的最终shepardsflag值应该是= 3(Foll),因为它应该只接受“联邦法院”的行并忽略其余的行。
但目前的结果是shepardsflag = 2;这是错误的
我希望我解释得很好。
有人可以帮助我正确的逻辑吗?我应该创建一个临时表吗?提前致谢。
脚本:
ALTER PROCEDURE [dbo].[spUpdateShepardsFlags] @caseid int = null AS
begin
declare @Shep int
declare @ref_caseid int
declare @court int
declare @courtFC int
declare @annot int
if @caseid is not null
begin
select @court = b.court, @ref_caseid = a.ref_caseid, @annot = a.annotation
from cba_annot a inner join cbm_case b on a.ref_caseid = b.caseid
where a.src_caseid = @caseid
if @court is not null
begin
if @court = 'MYFC'
set @courtFC = @courtFC + 1
if @court <> 'MYFC'
SET @courtFC = @courtFC + 0
PRINT 'The @courtFC counter : ' + CAST(@courtFC AS CHAR)
end
if @court is not NULL
begin
if @courtfc > 0
begin
if exists(select a.ref_caseid, b.court, a.annotation, a.src_caseid from
cba_annot a inner join cbm_case b on a.ref_caseid = b.caseid)
begin
if exists(select src_caseid from cba_annot where (annotation like '%Refd%'
or annotation like '%Comp%')
and src_caseid = @caseid)
set @Shep = 4
if exists(select src_caseid from cba_annot where (annotation like '%Foll%'
or annotation like '%Aff%')
and src_caseid = @caseid)
set @ShepFC = 3
update cbm_case
set shepardsflag = @shep
where [email protected]
end
end
else -- if @courtFC = 0
begin --new
if exists(select a.ref_caseid, b.court, a.annotation, a.src_caseid from
cba_annot a inner join cbm_case b on a.ref_caseid = b.caseid)
begin
if exists(select src_caseid from cba_annot where (annotation like '%Refd%'
or annotation like '%Comp%')
and src_caseid = @caseid)
set @Shep = 4
if exists(select src_caseid from cba_annot where (annotation like '%Foll%'
or annotation like '%Aff%')
and src_caseid = @caseid)
set @Shep = 3
if exists(select src_caseid from cba_annot where (annotation like '%Not Foll%'
or annotation like '%Dist%')
and src_caseid = @caseid)
set @Shep = 2
update cbm_case
set shepardsflag = @shep
where [email protected]
end
end -- new
end
else --- if court is NULL -- case not referred by any other case
update cbm_case
set shepardsflag = 5
where [email protected]
end
else -- if caseid is null
-- other condition
你得到了这个答案吗? –