2012-06-11 62 views
-1

好,第一個問題比較和你們嚇唬我,你知道多少,所以請溫柔...如何將多個值一列對分隔字符串中的存儲過程

我想傳入分隔字符串並將其轉換爲存儲過程中的數組,然後使用該數組檢查列中的值。這是抓住。我試圖採用預先存在的表格,該表格檢查一個關聯並將其展開以允許多個關聯。

所以列annAssociations可能有三個ID,4,16,32,但我需要檢查它是否屬於被查詢的groupIds,6,12,32。由於其中一個值匹配,它應該返回該行。

以下是存在的過程。

CREATE PROCEDURE [dbo].[sp_annList] 
-- Date Range of Announcements. 
@dateBegin datetime, 
@dateEnd datetime, 
    -- Announcement type and associations. 
@annType varchar(50), 
@annAssociation varchar(255) 

AS 
BEGIN 

-- Set the SELECT statement for the announcements. 
SET NOCOUNT ON; 
-- See if this should be a limited query 
IF @annAssociation <> '' 
    Begin 
     SELECT * 
     FROM announcements 
     WHERE (date1 <= @dateEnd AND date2 >= @dateBegin) -- See if the announcement falls in the date range. 
      AND annType = @annType -- See if the announcement is the right type. 
      AND annAssociations LIKE (select SplitText from dbo.fnSplit(@annAssociation, ',')) 
     ORDER BY title 
    END 
Else 
    Begin 
     SELECT * 
     FROM announcements 
     WHERE (date1 <= @dateEnd AND date2 >= @dateBegin) 
      AND annType = @annType 
     ORDER BY title 
    End 
END 

這裏是我用來轉換分隔字符串並將其存儲在臨時表中的方法。

CREATE Function [dbo].[fnSplit](@text text, @delimitor nchar(1)) 

RETURNS 
@table TABLE 
(
[Index] int Identity(0,1), 
[SplitText] varchar(10) 
) 
AS 

BEGIN 
declare @current varchar(10) 
declare @endIndex int 
declare @textlength int 
declare @startIndex int 

set @startIndex = 1 

if(@text is not null) 
begin 
    set @textLength = datalength(@text) 

    while(1=1) 
    begin 
     set @endIndex = charindex(@delimitor, @text, @startIndex) 

     if(@endIndex != 0) 
     begin 
      set @current = substring(@text,@startIndex, @endIndex - @StartIndex) 
      Insert Into @table ([SplitText]) values(@current) 
      set @startIndex = @endIndex + 1 
     end 
     else 
     begin 
      set @current = substring(@text, @startIndex, datalength(@text)[email protected]+1) 
      Insert Into @table ([SplitText]) values(@current) 
      break 
     end 
    end 

end 

return 
END 

很抱歉的長期問題。我只是想讓所有的信息在那裏。我一直在研究數天,而且我不知道去哪裏尋找,或者錯過了一些明顯的東西。

回答

0

你可能不會得到更好的性能比這種方法(當然你可能會看到一個CLR分割功能,但在3個或4個項目更好的性能,你不會看到太大的區別):

SELECT * 
    FROM announcements AS a 
    WHERE ... 
    AND EXISTS (SELECT 1 FROM dbo.fnSplit(@annAssociation) AS n 
    WHERE ',' + a.annList + ',' LIKE '%,' + n.SplitText + ',%'); 

這裏的關鍵是你只需要拆分其中一個列表。

真的應停止在annAssocations列中存儲多個值。每個id是一個獨立的數據片段,應單獨存儲(除了更好地符合規範化之外,它將使查詢更簡單)。

+0

我知道。數據庫最初只建立一個關聯,然後一些白癡有一個聰明的想法有多重關聯。那當然是我了。我的計劃是在沒有時間緊迫的情況下返回並重做整個結構。無論如何,我最終可能會回去。半夜多幾點時間......感謝您的幫助。這讓我走了。 – edumacator

相關問題