2011-12-29 147 views
0

我有一個存儲過程GetReportItems拆分字符串參數並選擇該字符串數組?

GetReportItems 

@ItemId varchar(max) 

SELECT rt.ReportName, rt.ReportId, rg.OriginatedFrom 
FROM Reports rt 
    JOIN ReportOrigin rg on rg.ReportId = rt.ReportId 
     WHERE rt.ColA = SUBSTRING(@ItemId, 1, 3) 
     AND rt.ColB = SUBSTRING(@ItemId, 4, Len(@ItemId) - 3) 

@ItemId我可以將它傳遞給像:ABC123ZDEF3456YGHI7890X,這一切工作正常。

但我需要更新此存儲過程允許:

  1. 傳中ABC123Z~DEF3456Y~GHI7890X@ItemId,參數的存儲過程。
  2. 存儲過程拆分@ItemId字符串~並且在每個字符串上調用SELECT

我怎麼能做到1和2以上? 即使我將多個參數傳遞給存儲過程,如何在所有這些參數上聚合SELECT

+1

這是從錯誤的地方開始。根本分裂項目已經夠糟了;試圖處理可變長度的物品清單是不是很明智。我不確定推薦什麼作爲替代方案。我可能會使用具有兩列的臨時表,ColA部分和字符串的ColB部分。然後,我將加載表中要搜索的值,然後將查詢作爲主表和臨時表的連接。 – 2011-12-29 23:22:05

回答

1

臨時表是你的朋友在這裏。 :)把你的@ItemID分成臨時表,然後把你的報告加入臨時表。

-- We need some variables for working with the data 
DECLARE @Sep Char, 
      @SepPos Int 
SET @Sep = '~' 

-- We need a place to store our arguments 
CREATE TABLE #Values (Val1 VarChar(3), Val2 VarChar(50)) 

SELECT @SepPos = CharIndex (@Sep, @ItemID) 
WHILE @SepPos > 0 BEGIN 
    -- Parse the leading argument into the temp table 
    INSERT INTO #Values (Val1, Val2) 
    SELECT SubString (@ItemID, 1, 3), 
      SubString (@ItemID, 4, @SepPos - 4) 

    -- Remove the leading argument from the argument string 
    SELECT @ItemID = SubString (@ItemID, @SepPos + 1, Len (@ItemID)) 
    -- Find the next separator 
    SELECT @SepPos = CharIndex (@Sep, @ItemID) 
END 
-- On the last loop, it won't have a separator, so we'll end up with 
-- one last argument to parse into our temp table 
INSERT INTO #Values (Val1, Val2) 
SELECT SubString (@ItemID, 1, 3), 
     SubString (@ItemID, 4, Len (@ItemID) - 3) 

-- Now join to our report 
SELECT * 
FROM  Reports rt 
    JOIN ReportOrigin rg ON rg.ReportId = rt.ReportId 
    JOIN #Values ON 
     rt.ColA = #Values.Val1 AND rt.ColB = #Values.Val2