我有一个存储以下内容的表:
JobID
ValidationItemID
CreatedBy
我希望能够插入到这个表(一个预定义的模板)中,但只添加不存在的行。我的意思是不存在是 JobID 和 ValidationItemID 的组合使行唯一。我的过程传入了 JobID,但我无法传入验证项 ID,因为我将此列作为模板的一部分...
有这样的效果:
CREATE PROCEDURE insTemplate
@JobID varchar(50),
@Login varchar(50)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
INSERT INTO
ValidationItemSignOff
(
JobID,
ValidationItemID,
CreatedBy
)
SELECT
DISTINCT
@JobID,
vi.ValidationItemID,
@Login
FROM
RunOffAnswer roa
INNER JOIN
Method m ON m.MethodID = roa.MethodID
INNER JOIN
RunOffValidationItem vi ON vi.ValidationItemID = m.ValidationItemID
WHERE
vi.Inactive=0
AND NOT EXISTS(SELECT * FROM ValidationItemSignOff WHERE JobID=@JobID AND vi.ValidationItemID ???
END
GO
我不知道如何表达 where 条件,以便它不会重新插入相同的 JobID 和 ValidationItemID。可以说我在桌子里面:
Job ValidationItem
Job A 1
Job A 2
Job A 5
我有一个包含以下内容的模板:
ValidationItem
1
2
3
4
5
6
当我运行我的存储过程时,它应该只从模板表中插入值 3、4、6,用于作业 id ......所以我需要关于 where 条件的帮助。
我认为我的问题是我不能使用NOT EXISTS
,也许我需要重新加入到这个 ValidationItemSignOff 表本身,JobID
并且ValidationItemID
在哪里ValidationItemID
是 NULL,可能是这样的:
CREATE PROCEDURE insTemplate
@JobID varchar(50),
@Login varchar(50)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
INSERT INTO
ValidationItemSignOff
(
JobID,
ValidationItemID,
CreatedBy
)
SELECT
DISTINCT
@JobID,
vi.ValidationItemID,
@Login
FROM
RunOffAnswer roa
INNER JOIN
Method m ON m.MethodID = roa.MethodID
INNER JOIN
RunOffValidationItem vi ON vi.ValidationItemID = m.ValidationItemID
RIGHT OUTER JOIN
ValidationItemSignOff viso ON viso.JobID = @JobID
AND viso.ValidationItemID = vi.ValidationItemID
WHERE
vi.Inactive=0
AND viso.ValidationItemID IS NULL
END
GO
明白了我觉得
用这个替换右连接:
LEFT JOIN
ValidationItemSignOff viso
ON viso.JobID = @JobID
AND viso.ValidationItemID = vi.ValidationItemID