合并多表插入?

时间:2013-08-26 17:57:59

标签: sql sql-server merge sql-server-2008-r2

我正在尝试在父/子关系中插入一些行。我知道如何在.NET中执行此操作但无法退出在T-SQL中获取它。

这将是我用来查找我要插入的信息的基本查询:

SELECT * FROM parentTable p
INNER JOIN childTable c
    ON p.ID = c.ParentTableID
WHERE p.PlanID = 123456

我需要首先插入ParentTable行,它实际上只是匹配行的副本,但具有新的PlanID和创建日期。然后我从插入的行中获取该ParentTable ID,并将其用于相同的进程,但用于子表。

所以我需要在.Net中说至少是我遍历所有parentTable匹配的地方,并为每个匹配创建1个childTable行。

我试图使用MERGE和OUTPUT子句,但似乎我可能使用方形钉来做圆孔。我会更好地使用某种类型的CURSOR吗?


所以这是我到目前为止基于下面的答案。不幸的是,它没有抓住SCOPE_IDENTITY() ......它有诀窍吗?因为那是返回NULL我在插入时得到FK错误。

USE MemberCenteredPlan

DECLARE @NewPlanID BIGINT;--49727690
DECLARE @OldPlanID BIGINT;--49725211
DECLARE @NewSWReAssID BIGINT;

SET @NewPlanID = 49727690
SET @OldPlanID = 49725211

BEGIN
INSERT INTO tblSocialWorkerReAssessment 
SELECT 
    @NewPlanID
    ,[Discussed]
    ,Discussion
    ,NULL
    ,NULL
    ,NULL   
    ,CreatedBy
    ,GETDATE()
    ,NULL
    ,NULL
    FROM tblSocialWorkerReAssessment
    WHERE PlanID = @OldPlanID

SELECT @NewSWReAssID = SCOPE_IDENTITY();

INSERT INTO tblPlanDomain
SELECT 
   @NewPlanID
   ,[DomainTypeID]
   ,[MemberOutcomes]
   ,[MemberPreferences]
   ,[DomainDate]
   ,[Steps]
    ,[ClinicalFunctionalConcerns]
    ,[ReportWageES]
    ,[ReportWageSSA]
    ,@NewSWReAssID
    ,[CreatedBy]
   ,GETDATE()
   ,NULL
   ,NULL   
   ,NEWID()
FROM tblPlanDomain 
WHERE planID = @OldPlanID

END

2 个答案:

答案 0 :(得分:2)

您不需要MERGE,但您绝对不需要游标。并且INSERT(或MERGE)一次只能影响一个表,因此您无论如何都需要执行多个语句。如果您一次只处理一个计划,可以这样做:

DECLARE @NewPlanID INT;

INSERT dbo.ParentTable(cols...) 
  SELECT cols...
  FROM dbo.ParentTable WHERE PlanID = 123456;

SELECT @NewPlanID = SCOPE_IDENTITY();

INSERT dbo.ChildTable(ParentTableID, cols...) 
  SELECT @NewPlanID, cols...
  FROM dbo.ChildTable WHERE PlanID = 123456;

如果你需要引用多个新计划,它会变得有点复杂,在这种情况下你需要使用MERGE(目前,INSERT的可组合DML是一个光线方面很少 - 您无法在OUTPUT子句中引用源表。

DECLARE @p TABLE(OldPlanID INT, NewPlanID INT);

MERGE dbo.ParentTable WITH (HOLDLOCK)
USING 
(
  SELECT ID, cols... FROM dbo.ParentTable 
  WHERE ID IN (123456, 234567)
) AS src ON src.ID IS NULL
WHEN NOT MATCHED THEN INSERT(cols...)
VALUES(src.cols...)
OUTPUT src.ID, inserted.ID INTO @p;

INSERT dbo.ChildTable(ParentTableID, cols...)
SELECT p.NewPlanID, t.cols... 
FROM dbo.ChildTable AS t
INNER JOIN @p AS p
ON t.ParentTableID = p.OldPlanID;

但是,您应该对此非常谨慎......我在this answer over on dba.SE中使用MERGE链接到几个问题和未解决的错误。我还posted a cautionary tip here

答案 1 :(得分:0)

我认为这就是你所追求的目标。

Use Northwind
GO

SET NOCOUNT ON


IF OBJECT_ID('tempdb..#OrderAuditHolder') IS NOT NULL
begin
        drop table #OrderAuditHolder
end


CREATE TABLE #OrderAuditHolder 
( 
    [OriginalOrderID] [int] NOT NULL,
    [NewOrderID] [int] NOT NULL,
    [CustomerID] [nchar](5) NULL,
    [EmployeeID] [int] NULL,
    [OrderDate] [datetime] NULL,
    [RequiredDate] [datetime] NULL,
    [ShippedDate] [datetime] NULL,
    [ShipVia] [int] NULL,
    [Freight] [money] NULL,
    [ShipName] [nvarchar](40) NULL,
    [ShipAddress] [nvarchar](60) NULL,
    [ShipCity] [nvarchar](15) NULL,
    [ShipRegion] [nvarchar](15) NULL,
    [ShipPostalCode] [nvarchar](10) NULL,
    [ShipCountry] [nvarchar](15) NULL,
)


declare @ExampleOrderID int
select @ExampleOrderID = (select top 1 OrderID from dbo.Orders ords where exists (select null from dbo.[Order Details] innerOD where innerOD.OrderID = ords.OrderID ) )

print '/@ExampleOrderID/'
print @ExampleOrderID
print ''


insert into dbo.Orders (CustomerID,EmployeeID,OrderDate,RequiredDate,ShippedDate,ShipVia,Freight,ShipName,ShipAddress,ShipCity,ShipRegion,ShipPostalCode,ShipCountry)
output @ExampleOrderID , inserted.OrderID,inserted.CustomerID,inserted.EmployeeID,inserted.OrderDate,inserted.RequiredDate,inserted.ShippedDate,inserted.ShipVia,inserted.Freight,inserted.ShipName,inserted.ShipAddress,inserted.ShipCity,inserted.ShipRegion,inserted.ShipPostalCode,inserted.ShipCountry
into #OrderAuditHolder
Select 
CustomerID,EmployeeID,OrderDate,RequiredDate,ShippedDate,ShipVia,Freight,ShipName,ShipAddress,ShipCity,ShipRegion,ShipPostalCode,ShipCountry
from dbo.Orders where OrderID = @ExampleOrderID

print '/#OrderAuditHolder/'
Select * from #OrderAuditHolder
print ''

Insert into dbo.[Order Details] ( OrderID , ProductID , UnitPrice , Quantity , Discount )
Select 
holder.NewOrderID , od.ProductID , od.UnitPrice , od.Quantity , od.Discount
from #OrderAuditHolder holder
join dbo.[Order Details] od on holder.OriginalOrderID = od.OrderID
/* Note, the "join" is on the OriginalOrderID, but the inserted value is the NewOrderID */


/* below is not needed, but shows results */
declare @MaxOrderID int
select @MaxOrderID = (select MAX(OrderID) from dbo.Orders ords where exists (select null from dbo.[Order Details] innerOD where innerOD.OrderID = ords.OrderID ) )
select * from dbo.[Order Details] where OrderID = @MaxOrderID order by OrderID desc
/**/



IF OBJECT_ID('tempdb..#OrderAuditHolder') IS NOT NULL
begin
        drop table #OrderAuditHolder
end



SET NOCOUNT OFF