下面的更新声明按预期工作。但是,我需要将语句循环50次。我尝试编写一个循环,允许我更改从Seg1到SegX设置的字段,并更新SubString(GoalBusinessSegment,(6 * 1)-5,5)AS' Seg& #39;到SubString(GoalBusinessSegment,(6 * X)-5,5)AS' Seg'
UPDATE [dbo].[MULTBUSSEGTEST]
SET Seg1 = SegTBL.Seg
FROM (SELECT DISTINCT GoalBusinessSegment,SubString(GoalBusinessSegment,(6*1)-5,5) AS 'Seg'
FROM [2017].[dbo].[WPGDM]
WHERE GoalID BETWEEN 22.1 AND 22.4 AND
LEFT(GoalBusinessSegment,1) = 'B' AND LEN(GoalBusinessSegment) > 5
) SegTBL
WHERE [dbo].[MULTBUSSEGTEST].SegID = SegTBL.GoalBusinessSegment
以下是我在循环中的尝试。
DECLARE @LoopCount int
DECLARE @SegField varchar(255)
DECLARE @i int
DELETE FROM [dbo].[MULTBUSSEGTEST]
INSERT INTO [dbo].[MULTBUSSEGTEST]
SELECT DISTINCT GoalBusinessSegment AS 'SegID'
,NULL AS 'Seg1'
,NULL AS 'Seg2'
,NULL AS 'Tgt1'
,NULL AS 'Tgt2'
,NULL AS 'Act1'
,NULL AS 'Act2'
FROM [2017].[dbo].[WPGDM]
WHERE GoalID BETWEEN 22.1 AND 22.4 AND LEFT(GoalBusinessSegment,1) = 'B' AND LEN(GoalBusinessSegment) > 5
Set @LoopCount = (SELECT FLOOR(MAX(LEN(GoalBusinessSegment))/5)
FROM [2017].[dbo].[WPGDM]
)
WHILE @i <= @LoopCount
BEGIN
Set @SegField = 'Seg' + @LoopCount
UPDATE [dbo].[MULTBUSSEGTEST]
SET @SegField = SegTBL.Seg
FROM (SELECT DISTINCT GoalBusinessSegment
,SubString(GoalBusinessSegment,(6*@i)-5,5) AS 'Seg'
FROM [2017].[dbo].[WPGDM]
WHERE GoalID BETWEEN 22.1 AND 22.4 AND LEFT(GoalBusinessSegment,1) = 'B' AND LEN(GoalBusinessSegment) > 5
) SegTBL
WHERE [dbo].[MULTBUSSEGTEST].SegID = SegTBL.GoalBusinessSegment
SET @i = @i + 1
END
循环产生所有空值,我缺少什么?
答案 0 :(得分:0)
意识到不需要多个字段和更新语句。问题解决了。