拆分字符串参数并选择该字符串数组?
问题描述:
我有一个存储过程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
我可以将它传递给像:ABC123Z
或DEF3456Y
或GHI7890X
,这一切工作正常。
但我需要更新此存储过程允许:
- 传中
ABC123Z~DEF3456Y~GHI7890X
为@ItemId
,参数的存储过程。 - 存储过程拆分
@ItemId
字符串~
并且在每个字符串上调用SELECT
。
我怎么能做到1和2以上? 即使我将多个参数传递给存储过程,如何在所有这些参数上聚合SELECT
?
答
临时表是你的朋友在这里。 :)把你的@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
这是从错误的地方开始。根本分裂项目已经够糟了;试图处理可变长度的物品清单是不是很明智。我不确定推荐什么作为替代方案。我可能会使用具有两列的临时表,ColA部分和字符串的ColB部分。然后,我将加载表中要搜索的值,然后将查询作为主表和临时表的连接。 – 2011-12-29 23:22:05