0

我有一个 SP,它应该将从一个函数生成的 2 个临时表与另一个表进行比较。我的问题是,它不是逐步遍历每个临时表,而是同时遍历两个临时表。我不确定如何编写代码来一次遍历每个表以获得所需的结果。

    DROP PROCEDURE uspJudgments;
GO
CREATE PROCEDURE uspJudgments 
@fullName varchar(100), @fullName1 varchar(100)
AS
BEGIN

SELECT *
INTO #tmpFullname
FROM dbo.DelimitedSplit8K(@fullName, ',')

SELECT *
INTO #tmpFullname1
FROM dbo.DelimitedSplit8K(@fullName1, ',')

SELECT *
FROM #tmpFullName

SELECT *
FROM #tmpFullName1

DECLARE @MaxRownum int
SET @MaxRownum = (SELECT MAX(ItemNumber) FROM #tmpFullname)

DECLARE @Iter int
SET @Iter = (SELECT MIN(ItemNumber) FROM #tmpFullname)

DECLARE @MaxRownum1 int
SET @MaxRownum1 = (SELECT MAX(ItemNumber) FROM #tmpFullname1)

DECLARE @Iter1 int
SET @Iter1 = (SELECT MIN(ItemNumber) FROM #tmpFullname1)

DECLARE @Name varchar(25)
DECLARE @Name1 varchar(25)


WHILE @Iter <= @MaxRownum AND @iter1 <= @Maxrownum1

BEGIN

    SET @Name = (SELECT Item FROM #tmpFullname WHERE ItemNumber = @Iter)   
    SET @Name1 = (SELECT Item FROM #tmpFullname1 WHERE ItemNumber = @Iter1)   
    SELECT *
    --INTO #tmpDefSelect
    FROM defendants_ALL 
    WHERE combined_name LIKE '%' + @Name + '%' AND combined_name LIKE '%' + @Name1 + '%';

    SET @Iter = @Iter + 1
    SET @Iter1 = @Iter1 + 1
END

END


DROP TABLE #tmpFullname
DROP TABLE #tmpFullname1

EXEC uspJudgments @fullName = 'grein,smit', @fullName1 = 'joh,jon,j.'

我需要得到 grein 的所有结果——joh、jon、j。和 smit, joh, jon, j。

目前,上述代码仅返回 grein joh AND smit, jon.. 在我们的数据库中,第一个组合没有返回任何结果,而 jonathon smith 和 jon smith 则返回 38 个结果。如何正确遍历每个临时表以获得所需的结果?

4

1 回答 1

1

您只能得到这两种组合grein joh,并且smith jon由于您迭代@Iter和的方式@iter1。您同时增加它们两个。你需要一个像这样的嵌套循环:

declare @start_val integer = @iter1

while @Iter <= MaxRownum
begin

  set @iter1 = @start_val

  while @iter1 <= @Maxrownum1
  begin

    set @Name = ...
    set @Name1 = ...

    ...

    set @iter1 = @iter1 + 1
  end

  set @Iter = @Iter + 1
end

但我认为你甚至不需要WHILE循环:

select d.*
from   defendants_ALL, #tmpFullname t1, #tmpFullname1 t2
where  d.combined_name = t1.Item + ' ' + t2.Item

或者(如果您仍然需要使用LIKE):

select d.*
from   defendants_ALL, #tmpFullname t1, #tmpFullname1 t2
where  d.combined_name like '%' + t1.Item + '%'
  and  d.combined_name like '%' + t2.Item + '%'

(所有 SQL 都未经测试...)

于 2012-10-20T02:33:41.473 回答