CharIndex用于选择全字搜索的行

时间:2013-04-04 07:51:40

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

我编写了以下SQL查询。我只想回归“纽约”和“新泽西”。但我的数据集随之返回“新”。

查询:

DECLARE @charToSerch nvarchar(100)

SET @charToSerch='New York,New Jersy'

Create table #Temp
(
        Name nvarchar(100)
)

INSERT into #temp(Name) values('New')
INSERT into #temp(Name) values('New York')
INSERT into #temp(Name) values('New Jersy')
INSERT into #temp(Name) values('Dellas')
INSERT into #temp(Name) values('Laligam')

Select * FROM #temp where charindex(Name,'New York,New Jersy')>0

DROP table #temp

数据集如下所示。

Name
---------
New
New York
New Jersy

请帮我解决这个问题。

先谢谢

2 个答案:

答案 0 :(得分:1)

创建将字符串拆分为行的函数。

CREATE FUNCTION [dbo].[uf_SplitIntoTable](@String varchar(max), @Delimiter char(1))     
RETURNS @temptable TABLE (items varchar(500))     
AS     
BEGIN     
    DECLARE @idx int     
    DECLARE @slice varchar(max)     

    SELECT @idx = 1     
        IF len(@String)<1 or @String is null  RETURN     

    WHILE @idx!= 0     
    BEGIN
        SET @idx = CHARINDEX(@Delimiter,@String)     
        IF @idx!=0     
            SET @slice = left(@String,@idx - 1)     
        ELSE     
            SET @slice = @String     

        IF(LEN(@slice)>0)
            INSERT INTO @temptable(Items) VALUES(LTRIM(RTRIM(@slice)))     

        SET @String = right(@String,len(@String) - @idx)     
        IF LEN(@String) = 0 BREAK     
    END 

    /* удаляем повторяющиеся ключи */
    ;WITH CTE(N) AS
    (
        SELECT ROW_NUMBER() OVER(PARTITION BY items ORDER BY items)
        FROM @temptable
    )
        DELETE CTE WHERE N>1;

RETURN     
END

并以这种方式使用

Select *
FROM #temp t
     join dbo.uf_SplitIntoTable(@charToSerch,',') s on t.Name=s.items

答案 1 :(得分:0)

我认为正确的sql是:

Select * FROM #temp where charindex('New York',Name)>0 or Charindex('New Jersy',Name)>0

有关Patindexcharindex

的信息