2013-04-04 91 views
1

我寫了下面的SQL查詢選擇行。我只想回到「紐約」和「新澤西州」。但是我的數據集與它一起返回「新」。CHARINDEX與全詞搜索

查詢:

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 

請幫我簡寫一下這個問題。

由於提前

回答

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 
+0

它的工作...感謝 – Gowdhaman008 2013-04-04 08:28:36

+0

@ Gowdhaman008歡迎您。 – 2013-04-04 08:36:55

0

正確的SQL,我認爲是:

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

信息約Patindexcharindex