1

我编写了以下 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

请帮我解决这个问题。

提前致谢

4

2 回答 2

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
于 2013-04-04T08:09:37.400 回答
0

我认为正确的sql是:

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

关于Patindexcharindex 的信息

于 2013-04-04T08:04:23.187 回答