SQL:匹配整个字符串未排序

时间:2014-12-29 20:13:47

标签: sql string stored-procedures cursor

我有一个参数(@FULL_NAME)填充了未分类的全名,使用逗号作为每个单词的分隔符。我想选择一个表的所有行,其中包含此参数中的所有单词。

以下是一个例子,我正在寻找的人是:

  • 名字:“JUAN MARTIN”
  • 姓氏:“LOPEZ”

参数@FULL_NAME有谷歌:'MARTIN,LOPEZ,JUAN'

这是我用来查找行的代码:

DECLARE
    @SQL nvarchar(max),
    @FULL_NAME nvarchar(max),
    @AUX nvarchar(max)

SET @FULL_NAME = 'MARTIN,LOPEZ,JUAN'
SET @SQL = 'SELECT * FROM PEOPLE WHERE '

DECLARE AUX CURSOR FAST_FORWARD FOR (SELECT strval FROM dbo.Split(@FULL_NAME,','))
OPEN AUX

FETCH NEXT FROM AUX INTO @AUX
SET @SQL = @SQL + ''' '' + First_Name + '' '' + Last_Name + '' '' LIKE ''% ' + @AUX + ' %'''

FETCH NEXT FROM AUX INTO @AUX
WHILE @@FETCH_STATUS = 0
BEGIN
    SET @SQL = @SQL + ' AND '' '' + First_Name + '' '' + Last_Name + '' '' LIKE ''% ' + @AUX + ' %'''
    FETCH NEXT FROM AUX INTO @AUX
END 

CLOSE AUX
DEALLOCATE AUX

SELECT @SQL

有没有办法做到这一点?

谢谢!

2 个答案:

答案 0 :(得分:0)

你可以这样做。在People条件下使用表值函数dbo.Split加入Like表。这样的事情。

SELECT First_Name
FROM   PEOPLE A
       JOIN dbo.Split(@FULL_NAME, ',') B
         ON A.First_Name + ' ' + A.Last_Name LIKE '%' + B.strval + '%'
GROUP  BY first_name
HAVING Count (*) = (SELECT Count(*)
                    FROM   dbo.Split(@FULL_NAME, ',')) 

答案 1 :(得分:0)

SELECT * FROM PEOPLE 
WHERE First_Name + ' ' + Last_Name 
                        LIKE  '%' + PARSENAME(REPLACE(@FULL_NAME, ',','.') , 1) + '%'
 OR   First_Name + ' ' + Last_Name 
                        LIKE  '%' + PARSENAME(REPLACE(@FULL_NAME, ',','.') , 2) + '%'
 OR   First_Name + ' ' + Last_Name 
                        LIKE  '%' + PARSENAME(REPLACE(@FULL_NAME, ',','.') , 3) + '%'