开发者社区> 问答> 正文

用户存储程序的代码有些问题?

用户存储程序的代码有些问题?

展开
收起
贺贺_ 2019-12-02 23:22:31 526 0
1 条回答
写回答
取消 提交回答
  • 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
    
    2019-12-02 23:22:50
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
动态、高效,蚂蚁动态卡片的内核逻辑 立即下载
软件定义存储面向云的企业级存储 重构 立即下载
软件定义存储-面向云的企业级存储重构 立即下载