通过临时表更新和插入

时间:2019-04-02 09:07:48

标签: sql-server tsql stored-procedures

我试图使用存储过程一次更新多个记录,并且如果该记录不在表中,则必须将此记录作为新记录插入。我把ID作为桌子上的主键。我下面尝试的方法是首先将数据插入到临时表中,然后更新原始表。我使用了类似文章中的示例存储过程来创建它,因为我对编写存储过程有点陌生,所以在存储过程中会出错程序。请帮助

CREATE PROCEDURE [dbo].[xxxxxx]

DECLARE @Tbl  TABLE(
Id [int] NOT NULL PRIMARY KEY,
Payroll_Id [int],
ProductCode  nvarchar(255),
Description nvarchar (255),
Qty  nvarchar(255))


BEGIN


INSERT  INTO @Tb1 ([Payroll_Id],[ProductCode],[Description],[Qty])
 Select  @Paroll_Id as [Paroll_Id],@ProductCode as [ProductCode],@Description as [Description], @Qty as [Qty]

Update tps
Set [Payroll_Id]= tmp.Payroll_Id


,[ProductCode]= tmp.ProductCode
,[Description] = tmp.Description
,[Qty] = tmp.Qty
FROM dbo.SmLine tps
INNER JOIN @Tb1 tmp on tmp.Id= tps.Id
INSERT INTO SMLine ([Payroll_Id],[ProductCode],[Description],[Qty]) 
Select
tmp.Payroll_Id,tmp.ProductCode,tmp.Description,tmp.Qty
From @Tb1 tmp
LEFT JOIN dbo.SMLine tps ON tps.Id = tmp.Id
WHERE dbo.SmLine IS NULL
END

1 个答案:

答案 0 :(得分:0)

为此,我建议使用MERGE语句。

 MERGE dbo.destination_table AS target  
 USING 
 (
      /* SELECT statement for source data */
 ) AS source
 ON 
 (
     /* key column conditions to identify if record exits or not 
     i.e. target.id= source.id */
 )  
 WHEN MATCHED THEN   
    UPDATE SET Name = source.Name  
 WHEN NOT MATCHED THEN  
    INSERT 
    (
      /* some columns from target */
    )  
    VALUES 
    (
      /* some values from source */
    )