我创建了一个存储过程,接受7个参数并将值插入StagingTable(5条记录),然后检查StagingTable中的数据是否存在于FinalTable中。如果它不存在,请将值插入FinalTable。但是,当我运行该过程时,所有5条记录都插入到Staging表中,但只有1条记录插入到FinalTable中。我是用sql编写代码的新手,所以我不确定我的错误在哪里。
ALTER PROCEDURE [dbo].[sp_InsertBCCData_toStaging]
(-- Add the parameters for the stored procedure here
@JobNo varchar(50),
@Zip varchar(50),
@Country varchar(50),
@Copies varchar(50),
@AWB varchar(50),
@DelvCode varchar(50),
@OPSCode varchar(50)
)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
------tranfer the BCC values in tblImportBCCDataStaging Table
INSERT INTO dbo.tblImportBCCDataStaging (JobNo, Zip, Country, Copies, AWB, DelvCode, OPSCode)
VALUES (@JobNo, @Zip, @Country,@Copies,@AWB,@DelvCode, @OPSCode);
------tranfer the Staging records in tblImportBCCData Table
INSERT INTO dbo.tblImportBCCData (JobNo, Zip, Country, Copies, AWB, DelvCode, OPSCode)
SELECT JobNo, Zip, Country, Copies, AWB, DelvCode, OPSCode
FROM dbo.tblImportBCCDataStaging t
WHERE NOT EXISTS(SELECT JobNo FROM dbo.tblImportBCCData WHERE JobNo=T.JobNo);
END
答案 0 :(得分:0)
如评论中所述:所有记录都有相同的JobNo。如何修复上面的代码,以便即使它具有相同的JobNo也可以将它们全部插入?考虑检查WHERE
子句子查询中的非JobNo字段:
...
WHERE NOT EXISTS(SELECT JobNo FROM dbo.tblImportBCCData sub
WHERE sub.Zip = t.Zip
AND sub.Country = t.Country
AND sub.Copies = t.Copies
AND sub.AWB = t.AWB
AND sub.DelvCode = t.DelvCode
AND sub.OPSCode = t.OPSCode);
但是,考虑在临时表和最终表之间找到比JobNo
更独特的字段,以检查现有记录而不是所有字段。