在sql server中的多个游标中出现问题

时间:2014-12-23 07:43:49

标签: sql sql-server sql-server-2008

我有四个桌子的桌子

  • AGENTID
  • LicenceNumber
  • LineOfAuthority
  • 管辖权

我们假设我有一条带有以下值的记录

  • AgentId = 307
  • LicenceNumber = 245678
  • LineOfAuthority =“牙科服务,个人线路,伤亡”
  • Jurisdiction =“Alabama,New York”

...

...

类似地,我在此表中有其他具有不同值的记录

请注意,LineOfAuthority和Jurisdiction包含以逗号','分隔的多个值。

如果我将参数传递为

  • @AgentId = 307
  • @LineOfAuthority =“伤亡”
  • @Jurisdiction =“纽约”

然后输出

LicenceNumber = 245678

我的存储过程如下

ALTER PROCEDURE [dbo].[prLicenceFetchForAgentId]  

@LineOfAuthority nvarchar(max),
@Jurisdiction nvarchar(max),
@AgentId int

AS
Create table #tbLOA (
LOA nvarchar(max)
);

create table #tbtempJuris(
Jurisdiction nvarchar(max)
);

Insert into #tbLOA(LOA) Select LineOfAuthority from tbLicence where AgentId =@AgentId;
Insert into #tbtempJuris(Jurisdiction) Select Jurisdiction from tbLicence where AgentId =@AgentId;

DECLARE @LOASubString varchar(100);
DECLARE @JurisdictionSubString varchar(100);

-- first cursor

DECLARE @MyCursor CURSOR
SET @MyCursor = CURSOR FAST_FORWARD
FOR
Select LOA FROM #tbLOA
OPEN @MyCursor
FETCH NEXT FROM @MyCursor
INTO @LOASubString  

WHILE @@FETCH_STATUS = 0
BEGIN
-- second cursor

DECLARE @MyCursor2 CURSOR
SET @MyCursor2 = CURSOR FAST_FORWARD
FOR
Select LOA FROM #tbLOA
OPEN @MyCursor2
FETCH NEXT FROM @MyCursor2
INTO @JurisdictionSubString  

 WHILE @@FETCH_STATUS = 0
 BEGIN
 --second code

 if(@LOASubString = @LineOfAuthority and @JurisdictionSubString = @Jurisdiction)
 begin
 Select LicenceNumber from tbLicence where LineOfAuthority = @LOASubString
 and Jurisdiction=@JurisdictionSubString and AgentId =@AgentId;
 break;
 end

 FETCH NEXT FROM @MyCursor2
 INTO @JurisdictionSubString

 END

 CLOSE @MyCursor2
 DEALLOCATE @MyCursor2

 --end cursor 2

 FETCH NEXT FROM @MyCursor
 INTO @LOASubString

 END

CLOSE @MyCursor
DEALLOCATE @MyCursor

现在我无法得到正确的结果......它没有显示任何许可证号码...... 请帮帮我!!!

1 个答案:

答案 0 :(得分:2)

首先,在一列中包含多个值 第一种正常形式的数据库设计应该避免不惜一切代价!

其次,我不明白你用两个嵌套游标做了什么?!?!?!?

这似乎是一个非常简单的单SELECT语句:

 SELECT
     LicenceNumber 
 FROM 
     dbo.tbLicence 
 WHERE
     AgentId = @AgentId
     AND LineOfAuthority LIKE '%' + @LineOfAuthority + '%'
     AND Jurisdiction = LIKE '%' + @Jurisdiction + '%';