2013-02-01 65 views
3

我有兩個字符串作爲@CountryLocationIDs和@LocationIDs與價值觀:在兩個字符串比較數字在SQL Server

@CountryLocationIDs = 400,600,150,850,160,250 
@LocationIDs1  = 600,150,900 

然後,我需要在另一個變量輸出爲:

@LocationIDs = 400,600,150,850,160,250,900 

任何人請幫忙...提前致謝...

+4

看起來好像你付出denormalisation的價格。 –

回答

3

我已經創建了表值函數,它接受兩個參數,第一個是帶有ID的字符串,第二個是字符串中的分隔符。

CREATE FUNCTION [dbo].[Split](@String nvarchar(4000), @Delimiter char(1))  
returns @temptable TABLE (items nvarchar(4000))  
as  
begin  
    declare @idx int  
    declare @slice nvarchar(4000)  

    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(@slice)  

     set @String = right(@String,len(@String) - @idx)  
     if len(@String) = 0 break  
    end 
return  
end 

創建功能後,只要用這個方法UNION集合運算符:

EDITED

WITH ListCTE AS 
(
select items from dbo.split('400,600,150,850,160,250', ',') 
union 
select items from dbo.split('600,150,900', ',') 
) 
SELECT TOP 1 

    MemberList = substring((SELECT (', ' + items) 
          FROM ListCTE t2 
          ORDER BY 
           items 
          FOR XML PATH('') 
         ), 3, 1000)FROM ListCTE t1 

隨着UNION你會自動從兩個字符串得到不同的值,所以你不」 t需要使用DISTINCT子句

+0

我需要保存在一個varchar變量輸出...當試圖存儲,我得到的錯誤爲:Msg 512,Level 16 ,狀態1,過程spGetDLMembersByListType1,行51 子查詢返回多個值。當子查詢遵循=,!=,<, <= , >,> =或當子查詢用作表達式時,這是不允許的。 –

+1

編寫用於保存此輸出的代碼。 – veljasije

+0

SET @Location_IDs =((select * from dbo.SplitString(@CountryLocation_IDs,','))union(select * from dbo.SplitString(@Location_IDs,','))) –

0

This會幫你編程

你也可以參考this

+4

鏈接只有回答在這裏皺起了眉頭。如果您所鏈接的頁面被移動或刪除,該怎麼辦?將摘要包含到鏈接中會更有幫助。 –

+0

ohk ..我會在下次記住這一點..謝謝:) – KAsh

3

也可以使用選項w第i個動態管理功能sys.dm_fts_parser
你需要檢查全文組件腳本執行之前安裝:未安裝

SELECT FULLTEXTSERVICEPROPERTY ('IsFulltextInstalled') 

0 =全文。 1 =安裝了全文。 NULL =輸入無效或錯誤。

如果0 =全文沒有安裝那麼這個職位是需要你How to install fulltext on sql server 2008?

DECLARE @CountryLocationIDs nvarchar(100) = '400,600,150,850,160,250', 
     @LocationIDs1  nvarchar(100) = '600,150,900', 
     @LocationIDs  nvarchar(100) = N'' 

SELECT @LocationIDs += display_term + ',' 
FROM sys.dm_fts_parser('"'+ 'nn,' + @CountryLocationIDs + ',' + @LocationIDs1 + '"', 1033, NULL, 0) 
WHERE display_term NOT LIKE 'nn%' 
GROUP BY display_term 

SELECT LEFT(@LocationIDs, LEN(@LocationIDs) - 1) 
+0

+1。 –

+0

偉大的做法! +1 – TechDo

+0

賓果。感謝您的反饋;) –