CREATE PROCEDURE [dbo].[uspAddRows] @nmbr int
AS
BEGIN
SET NOCOUNT ON;
IF ISNULL(@nmbr, 0) <= 0
BEGIN
RAISERROR('@number must be positive', 16, 1);
RETURN;
END
IF EXISTS (SELECT name FROM sys.tables WHERE name = 'OrdersTemp1')
BEGIN
DROP TABLE OrdersTemp1
END
IF EXISTS (SELECT name FROM sys.tables WHERE name = 'Order detailsTemp1')
BEGIN
DROP TABLE [Order detailsTemp1]
END
CREATE TABLE dbo.OrdersTemp1 (OrderID int IDENTITY(1000,1), CustomerID nchar(5), EmployeeID int, OrderDate datetime, RequiredDate datetime,
ShippedDate datetime, ShipVia int, Freight money, ShipName nvarchar(40), ShipAddress nvarchar(60), ShipCity nvarchar(15), ShipRegion nvarchar(15),
ShipPostalCode nvarchar(10), ShipCountry nvarchar(15));
CREATE TABLE dbo.[Order detailsTemp1] (OrderID int, ProductID int, UnitPrice money, Quantity smallint, Discount real);
DECLARE @MyOrders TABLE
(
SourceOrderId INT PRIMARY KEY CLUSTERED,
NewOrderId INT
);
--merge for capturing the source s.OrderId
MERGE dbo.OrdersTemp1
USING
(
SELECT TOP (@nmbr) *
FROM Orders
ORDER BY OrderID
) AS s ON 1=2
WHEN NOT MATCHED THEN
INSERT (CustomerID, EmployeeID, OrderDate, RequiredDate, ShippedDate, ShipVia, Freight, ShipName, ShipAddress, ShipCity, ShipRegion, ShipPostalCode, ShipCountry)
VALUES (s.CustomerID, s.EmployeeID, s.OrderDate, s.RequiredDate, s.ShippedDate, s.ShipVia, s.Freight, s.ShipName, s.ShipAddress, s.ShipCity, s.ShipRegion, s.ShipPostalCode, s.ShipCountry)
OUTPUT s.OrderId, inserted.OrderId INTO @MyOrders(SourceOrderId, NewOrderId);
INSERT dbo.[Order detailsTemp1] (OrderID, ProductID, UnitPrice, Quantity, Discount)
SELECT m.NewOrderId, od.ProductID, od.UnitPrice, od.Quantity, od.Discount
FROM @MyOrders AS m
JOIN [Order Details] AS od ON m.SourceOrderId = od.OrderId;
--.... do stuff ...
END
GO
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。