该表包含项目的工作分解结构(每个项目具有项目级别(wbs1),阶段级别(wbs2)和任务级别(wbs3)
该表看起来像这样
Wbs1 wbs2 wbs3 name
262 ProjectA
262 01 Data Analsys
262 01 01 Data cleansing
262 01 02 Data Transforming
我需要使用insert语句向每个项目(WBS1)插入一个阶段(WBS2),例如添加一个wbs2" 02"到每个项目(wbs1)。
编写插入语句是没有问题的,我从项目级别选择数据,因为大多数都是多余的,所以没有问题,我只是不知道如何让它循环并将阶段添加到每个项目,因为那里是具有相同项目(wbs1)编号的多行
插入声明示例
Insert into dbo.pr ([WBS1],[WBS2],[WBS3],[Name])
(Select [WBS1],'999',[WBS3],'In-House Expenses'
from dbo.pr where wbs1 = @ProjectID
and wbs2 ='')
如何运行此语句以在每个项目中插入行?(wbs1)
希望这是有道理的。
答案 0 :(得分:0)
您可以使用带有添加的RowNumber字段的临时表,然后使用WHILE循环来处理每行的循环。然后,您可以在运行存储过程之前运行IF EXISTS作为条件检查。见下面的例子
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
DECLARE @ProjectId NVARCHAR(50) = '262'
CREATE TABLE #Temp (RowNumber INT, wbs1 NVARCHAR(255), wbs2 NVARCHAR(255), wbs3 NVARCHAR(255), name NVARCHAR(255))
INSERT INTO #Temp
SELECT ROW_NUMBER() OVER (ORDER BY wbs1, wbs2, wbs3, name)
,pr.*
FROM pr
select *
from #temp
-- Create loop variables to handle incremeting
DECLARE @Counter INT = 1;
DECLARE @MaxLoop INT = (SELECT COUNT(wbs1) FROM #temp)
WHILE @Counter <= @MaxLoop
BEGIN
-- Use if Exists to check the current looped meets whatever critiera you have
IF EXISTS (SELECT 'true'
FROM #Temp
WHERE RowNumber = @Counter
AND wbs1 = @ProjectId
AND wbs2 = ''
)
BEGIN
Insert into pr (wbs1,wbs2,wbs3,name)
(Select [WBS1],'999',[WBS3],'In-House Expenses'
from #temp where RowNumber = @Counter)
END
-- Remember to increment the counter
SET @Counter = @Counter + 1;
END
SELECT *
FROM pr
drop table #temp