我有一个表变量,其中填充了许多行。我想要实现的是循环遍历表变量的每一行,看看ID列是否存在于另一个标准表中,并将该行添加到新创建的表变量中。
我的代码如下:
DECLARE
@Intervention_ID int
SET @Intervention_ID = 969
/*---Check if intervention has pre-requisites---*/
DECLARE @PreRequisites TABLE
(
[Intervention_ID] int
)
INSERT INTO @PreRequisites
(
[Intervention_ID]
)
SELECT IP.[Requisite_ID]
FROM DI_Intervention_Prerequisites IP
WHERE
IP.[Intervention_ID] = @Intervention_ID
AND IP.[Prerequisite] = 1
/*---Check if pre-requisites have been completed---*/
DECLARE @Result TABLE
(
[Type_ID] int
, [Type_Name] nvarchar(max)
, [Intervention_ID] int
, [Intervention_Name] nvarchar(max)
)
WHILE NOT EXISTS
(
SELECT TOP 1 1
FROM DI_Employee_Intervention EI
WHERE
EI.[Intervention_ID] = (SELECT [Intervention_ID] FROM @PreRequisites)
)
INSERT INTO @Result
(
[Type_ID]
, [Type_Name]
, [Intervention_ID]
, [Intervention_Name]
)
正如您所看到的,我被困在代码的WHILE NOT EXISTS
部分。需要发生的是@PreRequisites
中DI_Employee_Intervention
中不存在@PreRequisites
中不存在的每一行,需要将@Result
行插入{{1}}。
答案 0 :(得分:2)
为什么不使用基于集合的方法而不是现在使用的RBAR(逐行排列)程序方法?
类似的东西:
INSERT INTO @Result([Type_ID], [Type_Name], [Intervention_ID], [Intervention_Name])
SELECT
... (some columns to match the columns of @Result)......
FROM
dbo.DI_Intervention_Prerequisites IP
WHERE
IP.[Intervention_ID] = @Intervention_ID
AND IP.[Prerequisite] = 1
AND NOT EXISTS (SELECT *
FROM DI_Employee_Intervention EI
WHERE EI.[Intervention_ID] = IP.[Intervention_ID] )
或类似的东西(我没有完全理解你的所有中间步骤以及你为什么采取它们......)