我有下面的代码,为什么我不想在@waitlistitmeID的临时表中获取最后一个值
10011没有被存储,虽然它的len是19并且应该被插入。 在查询中需要帮助。
DECLARE @pos INT
DECLARE @len INT
DECLARE @value VARCHAR(MAX)
declare @WaitlistItemID varchar(max)='10008,10009,10010,10011'
declare @MovingWaitListItems table ( WaitlistItemID int, WaitlistItemGUID numeric(16,0))
set @pos = 0
set @len = 0
while CHARINDEX(',', @WaitlistItemID, @pos+1)>0
BEGIN
set @len = CHARINDEX(',', @WaitlistItemID, @pos+1) - @pos
set @value = SUBSTRING(@WaitlistItemID, @pos, @len)
print @pos
print @len
print @value
INSERT INTO @MovingWaitListItems
SELECT WaitlistItemID, WaitlistItemGUID
FROM SXAAMWLWaitList
Where WaitlistItemID = @value
select * from @MovingWaitListItems
set @pos = CHARINDEX(',', @WaitlistItemID, @pos+@len) +1
print @pos
END
答案 0 :(得分:1)
对于上述内容,我想使用xml
节点方法,而不是使用substring()
,CHARINDEX()
函数
declare @WaitlistItemID varchar(max)='10008,10009,10010,10011'
declare @MovingWaitListItems table ( WaitlistItemID int, WaitlistItemGUID numeric(16,0))
;with cte as
(
select
a.value('.', 'varchar(max)') [WaitlistItemID] from
(
select CAST('<m>'+REPLACE(@WaitlistItemID, ',', '</m><m>')+'</m>' as xml) as waitlist
) w cross apply waitlist.nodes ('/m') as split(a)
)
INSERT INTO @MovingWaitListItems
select S.WaitlistItemID, S.WaitlistItemGUID from SXAAMWLWaitList S
JOIN CTE C ON C.[WaitlistItemID] = S.WaitlistItemID
select * from @MovingWaitListItems
答案 1 :(得分:0)
想象一下,如果你有一个带有单个元素10100
的@WaitlistItemID,你也会跳过它,因为你的循环条件是假的。
while CHARINDEX(',', @WaitlistItemID, @pos+1)>0
最后一个元素也是如此。所以你必须在循环结束时添加另一个交互
while ...
begin
end
set @len = LEN(@WaitlistItemID)
if @len > 0
BEGIN
set @value = SUBSTRING(@WaitlistItemID, @pos, @len)
INSERT INTO @MovingWaitListItems
SELECT WaitlistItemID, WaitlistItemGUID
FROM SXAAMWLWaitList
Where WaitlistItemID = @value
END