我是 SQL Server 2005 存储过程的初学者。我似乎无法让它按要求工作。
我有一个 sp 从名为annot
. @caseid
分配给列的值,src_caseid
并且在表中可以有多个引用 ( ref_caseid
) 或没有annot
。我想根据我使用 INNER JOIN 所做court
的表中的列设置条件并设置正确的 shepardsflag 。case
基本上是这样的场景:
- 表
annot
-ref_caseid, src_caseid, annotation
- 表
case
-caseid, court
INNER 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
,但似乎效果不佳。
从上面的示例中,案例 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 caseid=@caseid
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 caseid=@caseid
end
end -- new
end
else --- if court is NULL -- case not referred by any other case
update cbm_case
set shepardsflag = 5
where caseid=@caseid
end
else -- if caseid is null
-- other condition