在 SQL Server 2012 中,我有一个多次调用存储过程的脚本。循环将执行的次数与 [ResultHeader] 表中的记录数一样多。
EXEC [AS400].tp_SelectChildItems @Pgm, @Grp, @Pgmgrpseq,
null, null, null, null, null, @ItemSelection, null,
null, null, null, null,
注意:这个SP有一个table variable
内部
我有一个逗号分隔的 SelectedCostPageList 列表。对于此列表中的每个值,循环执行一次。
我正在观察一种奇怪的行为。当我从脚本调用 sp 时,只有 sp 第一次返回正确的记录。在随后的调用中,存储过程不返回任何记录。很奇怪…。当我更改逗号分隔字符串的顺序时,仅在第一次迭代时 sp 才返回记录。其他时候没有记录。
大家猜猜会是什么原因?
DECLARE @SelectedCostPageList VARCHAR(MAX)
SET @SelectedCostPageList = (SELECT (SELECT CONVERT(VARCHAR(32), A.PGM + '-'+A.GRP+'-'+A.PGMGRPSEQ) + ', ' AS [text()]
FROM dbo.[ResultHeader] A
WHERE UserId = 'U25703'
FOR XML PATH('')) AS CostPages) ResultHeader
PRINT @SelectedCostPageList
DECLARE @pos INT
DECLARE @len INT
set @pos = 0
set @len = 0
DELETE FROM ResultItems
WHILE CHARINDEX(',', @SelectedCostPageList, @pos+1)>0
BEGIN
set @len = CHARINDEX(',', @SelectedCostPageList, @pos+1) - @pos
DECLARE @SelectedCostPage VARCHAR(10)
set @SelectedCostPage = SUBSTRING(@SelectedCostPageList, @pos, @len)
set @pos = CHARINDEX(',', @SelectedCostPageList, @pos+@len) +1
PRINT @SelectedCostPage
DECLARE @Pgm AS VARCHAR (10);
DECLARE @Grp AS VARCHAR (10);
DECLARE @Pgmgrpseq AS VARCHAR (10);
SELECT @Pgm = (SELECT VALUE
FROM [AS400].[tf_SelectSplitString] (@SelectedCostPage, '-')
WHERE POSITION = 1);
PRINT @Pgm
SELECT @Grp = (SELECT VALUE
FROM [AS400].[tf_SelectSplitString] (@SelectedCostPage, '-')
WHERE POSITION = 2);
PRINT @Grp
SELECT @Pgmgrpseq = (SELECT VALUE
FROM [AS400].[tf_SelectSplitString] (@SelectedCostPage, '-')
WHERE POSITION = 3);
PRINT @Pgmgrpseq
Declare @ItemSelection as varchar(4000)
set @ItemSelection ='1116102540,1116102541';
print @ItemSelection
print 'HAI'
print @Pgmgrpseq
EXEC [AS400].tp_SelectChildItems
@Pgm, @Grp, @Pgmgrpseq,
null, null, null,
null, null, @ItemSelection, null,
null, null, null, null,
null, null, null, 1, 'U25703'
END
SELECT * FROM ResultItems
WHERE UserId = 'U25703'