如何在CASE中执行2个SQL语句

时间:2017-04-13 06:48:12

标签: sql-server tsql case

我有以下SQL查询语句:

INSERT INTO @mt_API
    SELECT 
        [dbo].fn_AddTimeZoneOffset(APHIST.ActionDate,'CET') AS ASDATE
        , [dbo].fn_AddTimeZoneOffset(APHIST.ReturnDate,'CET') AS ATDATE
        ,API_HIST.[ActionPlanItemID]
        ,API_HIST.[ActionPlanID]
        ,PIT.[ProductItemID]
        ,PIT.ProductItemCode
        ,PIT.QRCode
        ,PIT.Name
        ,ISNULL((SELECT TOP 1 mRSP.TotalRemainingAtStore FROM @mt_RemainingStockProduct AS mRSP 
            WHERE mRSP.InventoryDate <= APHIST.ReturnDate
            ORDER BY mRSP.InventoryDate DESC), 0) AS StoreTotalStock
        ,P.[Weight] AS ItemWeight
        ,M.UnitMeasureCode as Unit
        ,PIT.Quantity AS ItemQuantity
        ,P.ItemUnitWeight
        ,P.Quantity as ProductQuantity
        ,E1.FullName AS Emp1
        ,E2.FullName AS Emp2
        ,E3.FullName AS Emp3
        ,E4.FullName AS Emp4
        ,SECT.Name AS Sector
        ,CASE WHEN n=0 then 0 else [ItemStatus] end as [ItemStatus]
        ,APHIST.IsActionOver as ActionOver
    FROM 
        [Sales].[ActionPlanItem_History] AS API_HIST
    INNER JOIN 
        [Sales].[ActionPlan_History] AS APHIST On APHIST.ActionPlanID =  API_HIST.ActionPlanID
    INNER JOIN
        [Production].[ProductItem] AS PIT ON API_HIST.ProductItemID =PIT.ProductItemID
    INNER JOIN
        Production.Product as P ON PIT.ProductID = P.ProductID AND PIT.ProductID = P.ProductID AND 
            PIT.ProductID = P.ProductID
    INNER JOIN
        Production.UnitMeasure as M ON M.UnitMeasureID = P.WeightUnitMeasureID
    LEFT OUTER JOIN
        Sales.Employee AS E1 ON APHIST.EmployeeID1 = E1.EmployeeID 
    LEFT OUTER JOIN
        Sales.Employee AS E2 ON APHIST.EmployeeID2 = E2.EmployeeID 
    LEFT OUTER JOIN
        Sales.Employee AS E3 ON APHIST.EmployeeID3 = E3.EmployeeID 
    LEFT OUTER JOIN
        Sales.Employee AS E4 ON APHIST.EmployeeID4 = E4.EmployeeID 
    INNER JOIN
        Sales.Sector AS SECT ON APHIST.SectorID = SECT.SectorID
    INNER JOIN
        Production.ProductSubcategory as PS on P.ProductSubcategoryID=PS.ProductSubcategoryID
    INNER JOIN 
        Production.ProductCategory as PC on PS.ProductCategoryID= PC.ProductCategoryID

    CROSS APPLY (Values(0),(1)) d(n)
    WHERE  P.StoreID=@StoreID
    --WHERE PC.ProductCategoryID=@RootCategory AND P.StoreID=@StoreID

    --ORDER BY ProductItemCode, ATDATE 
    ORDER BY ASDATE , ProductItemCode

    SELECT 
         API1.ASDATE AS StartDate
        ,API1.ATDATE AS ReturnDate
        ,API1.ActionPlanItemID
        ,API1.ActionPlanID
        ,API1.ProductItemID
        ,API1.ProductItemCode
        ,API1.QRCode
        ,API1.Name
        ,API1.StoreTotalStock
        ,API1.ItemWeight
        ,API1.ItemQuantity
        ,API1.ItemUnitWeight
        ,API1.Unit
        ,API1.ProductQuantity
        ,API1.Emp1
        ,API1.Emp2
        ,API1.Emp3
        ,API1.Emp4
        ,API1.Sector
        ,API1.ItemStatus
        ,API1.ActionOver
        ,(API1.StoreTotalStock +
            (SELECT SUM(
                CASE API2.ItemStatus 
                    WHEN 0 THEN -1
                    WHEN 1 THEN 1 
                    ELSE 0 
                END * API2.ItemUnitWeight) 
            FROM @mt_API AS API2
                WHERE API2.ID <= API1.ID
            ) 

                -
            (

                **select 
                    case ISNULL(SUM([ProductItemWeight]), 0)
                        when 0 then 0
                        else SUM([ProductItemWeight])
                    end  
                from [ExplosiveTracking].[Production].[TransfertHistory]
                where stuff(convert(varchar(20),TransfertDateTime,120),17,6,'') < stuff(convert(varchar(20),API1.ASDATE,120),17,6,'')**



            ) 
        ) AS ItemWeightBal

    FROM @mt_API  AS API1 

CASE语句中我返回SUM([ProductItemWeight])如果它不是NULL,但是同时我需要在同一CASE内执行以下内容:

    delete from #tempTransfert
    where stuff(convert(varchar(20),#tempTransfert.TransferDate,120),17,6,'') < stuff(convert(varchar(20),API1.ASDATE,120),17,6,'')

增加更多测试:

如果我在一个独立的新查询中运行我想要完成的任务,那么DELETE和SELECT工作在CASE中查找

CREATE TABLE #tempTransfert 
(
 [ID] uniqueidentifier,
 [ProductId] int,
  [SourceId] int,
 TransferDate DateTime,
 TotalMovedProduct DECIMAL(16,4)
 )

 Insert into #tempTransfert
    select
        [ID],[ProductId], [SourceId], stuff(convert(varchar(20),TransfertDateTime,120),17,6,'') as TransferDate, SUM([ProductItemWeight]) as TotalMovedProduct
    from [ExplosiveTracking].[Production].[TransfertHistory]
    group by [ProductId],ID, [SourceId], stuff(convert(varchar(20),TransfertDateTime,120),17,6,'')


    select * from #tempTransfert


    MERGE #tempTransfert AS T
                    USING (select 
                        case ISNULL(SUM([ProductItemWeight]) , 0)
                        when 0 then 0 
                        else SUM([ProductItemWeight]) 
                        end  
                        , ID 
                        from [ExplosiveTracking].[Production].[TransfertHistory]
                        where stuff(convert(varchar(20),TransfertDateTime,120),17,6,'') < stuff(convert(varchar(20),'2017-02-28 15:38:00',120),17,6,'')
                        Group by ID
                        ) as S ([ProductItemWeight],ID)

                    ON (T.ID = S.ID)
                    WHEN MATCHED  
                        THEN DELETE;


BUT when I added in the complete query as below , I have a SYNTAX error near MERGE reported :

            DECLARE @m_StoreTotalStock AS DECIMAL(18,3)
        DECLARE @mt_API AS TABLE
        (
            ID INT IDENTITY(1,1),   ASDATE DATETIME,ATDATE DATETIME, 
            ActionPlanItemID INT,   ActionPlanID INT, 
            ProductItemID INT,      ProductItemCode VARCHAR(50),
            QRCode VARCHAR(50),     Name VARCHAR(50), 
            StoreTotalStock decimal(18,3), ItemWeight decimal(18,3),
            Unit VARCHAR(50),       ItemQuantity INT, 
            ItemUnitWeight DECIMAL(18,4), ProductQuantity INT, 
            Emp1 VARCHAR(50),       Emp2 VARCHAR(50), 
            Emp3 VARCHAR(50),       Emp4 VARCHAR(50), 
            Sector VARCHAR(50),     ItemStatus TINYINT,ActionOver INt
        )

        DECLARE @mt_RemainingStockProduct AS TABLE
        (
            StoreID  INT,InventoryDate DATETIME,ProductID INT, TotalRemainingAtStore DECIMAL(18,2)
        )

            CREATE TABLE #tempTransfert 
    (
     [ID] uniqueidentifier,
     [ProductId] int,
     [SourceId] int,
     TransferDate DateTime,
     TotalMovedProduct DECIMAL(16,4)
     )

     Insert into #tempTransfert
        select
            [ID],[ProductId], [SourceId], stuff(convert(varchar(20),TransfertDateTime,120),17,6,'') as TransferDate, SUM([ProductItemWeight]) as TotalMovedProduct
        from [ExplosiveTracking].[Production].[TransfertHistory]
        group by [ProductId],ID, [SourceId], stuff(convert(varchar(20),TransfertDateTime,120),17,6,'')


        select * from #tempTransfert

        /** Get Remaining StockBy Product **/
        INSERT INTO @mt_RemainingStockProduct
        (
            StoreID, InventoryDate, ProductID,TotalRemainingAtStore
        )
        --SELECT InventoryDate, SUM(TotalRemainingAtStore) AS TotalRemainingAtStore FROM 
        --(
            SELECT StoreID, InventoryDate, ProductID, SUM(Remaining) OVER (PARTITION BY StoreID ) AS TotalRemainingAtStore FROM
            (
                SELECT
                    P.StoreID, P.InventoryDate, P.ProductID, 
                    --SUM(PIT.Quantity * P.ItemUnitWeight)-SUM(PIT.UsedQuantity * P.ItemUnitWeight) AS Remaining
                  SUM(PIT.Quantity * P.ItemUnitWeight) AS Remaining
                FROM Sales.Store AS S
                    INNER JOIN Production.ProductItem AS PIT 
                    INNER JOIN Production.Product AS P ON PIT.ProductID = P.ProductID 
                    INNER JOIN Production.UnitMeasure AS UM ON P.WeightUnitMeasureID = UM.UnitMeasureID ON 
                        S.BusinessEntityID = P.StoreID
                    INNER JOIN Production.Location AS LOC ON S.BusinessEntityID = LOC.StoreID AND 
                        P.LocationID = LOC.LocationID AND P.LocationID = LOC.LocationID

                WHERE   (P.IsDeleted = 0) AND (PIT.IsDeleted = 0) AND P.StoreID = 4
                GROUP BY P.StoreID,P.InventoryDate, P.ProductID, UM.UnitMeasureCode, S.Name, LOC.MaxQuantity
            ) AS RST1
        --) AS RST2
        --GROUP BY RST2.InventoryDate 

        /** Endof Get Remaining StockBy Product **/

        -- Get Store total product items weight
        SELECT @m_StoreTotalStock = SUM(PIW.TotalWeight) 
        FROM dbo.v_ProductItemWeight AS PIW
        WHERE StoreID = 4

        INSERT INTO @mt_API
        SELECT [dbo].fn_AddTimeZoneOffset(APHIST.ActionDate,'CET') AS ASDATE
            , [dbo].fn_AddTimeZoneOffset(APHIST.ReturnDate,'CET') AS ATDATE
            ,API_HIST.[ActionPlanItemID]
            ,API_HIST.[ActionPlanID]
            ,PIT.[ProductItemID]
            ,PIT.ProductItemCode
            ,PIT.QRCode
            ,PIT.Name
            ,ISNULL((SELECT TOP 1 mRSP.TotalRemainingAtStore FROM @mt_RemainingStockProduct AS mRSP 
                WHERE mRSP.InventoryDate <= APHIST.ReturnDate
                ORDER BY mRSP.InventoryDate DESC), 0) AS StoreTotalStock
            ,P.[Weight] AS ItemWeight
            ,M.UnitMeasureCode as Unit
            ,PIT.Quantity AS ItemQuantity
            ,P.ItemUnitWeight
            ,P.Quantity as ProductQuantity
            ,E1.FullName AS Emp1
            ,E2.FullName AS Emp2
            ,E3.FullName AS Emp3
            ,E4.FullName AS Emp4
            ,SECT.Name AS Sector
            ,CASE WHEN n=0 then 0 else [ItemStatus] end as [ItemStatus]
            ,APHIST.IsActionOver as ActionOver
        FROM 
            [Sales].[ActionPlanItem_History] AS API_HIST
        INNER JOIN 
            [Sales].[ActionPlan_History] AS APHIST On APHIST.ActionPlanID =  API_HIST.ActionPlanID
        INNER JOIN
            [Production].[ProductItem] AS PIT ON API_HIST.ProductItemID =PIT.ProductItemID
        INNER JOIN
            Production.Product as P ON PIT.ProductID = P.ProductID AND PIT.ProductID = P.ProductID AND 
                PIT.ProductID = P.ProductID
        INNER JOIN
            Production.UnitMeasure as M ON M.UnitMeasureID = P.WeightUnitMeasureID
        LEFT OUTER JOIN
            Sales.Employee AS E1 ON APHIST.EmployeeID1 = E1.EmployeeID 
        LEFT OUTER JOIN
            Sales.Employee AS E2 ON APHIST.EmployeeID2 = E2.EmployeeID 
        LEFT OUTER JOIN
            Sales.Employee AS E3 ON APHIST.EmployeeID3 = E3.EmployeeID 
        LEFT OUTER JOIN
            Sales.Employee AS E4 ON APHIST.EmployeeID4 = E4.EmployeeID 
        INNER JOIN
            Sales.Sector AS SECT ON APHIST.SectorID = SECT.SectorID
        INNER JOIN
            Production.ProductSubcategory as PS on P.ProductSubcategoryID=PS.ProductSubcategoryID
        INNER JOIN 
            Production.ProductCategory as PC on PS.ProductCategoryID= PC.ProductCategoryID

        CROSS APPLY (Values(0),(1)) d(n)
        WHERE  P.StoreID=4
        --WHERE PC.ProductCategoryID=@RootCategory AND P.StoreID=@StoreID

        --ORDER BY ProductItemCode, ATDATE 
        ORDER BY ASDATE , ProductItemCode

        SELECT 
             API1.ASDATE AS StartDate
            ,API1.ATDATE AS ReturnDate
            ,API1.ActionPlanItemID
            ,API1.ActionPlanID
            ,API1.ProductItemID
            ,API1.ProductItemCode
            ,API1.QRCode
            ,API1.Name
            ,API1.StoreTotalStock
            ,API1.ItemWeight
            ,API1.ItemQuantity
            ,API1.ItemUnitWeight
            ,API1.Unit
            ,API1.ProductQuantity
            ,API1.Emp1
            ,API1.Emp2
            ,API1.Emp3
            ,API1.Emp4
            ,API1.Sector
            ,API1.ItemStatus
            ,API1.ActionOver
            ,(API1.StoreTotalStock +
                (SELECT SUM(
                    CASE API2.ItemStatus 
                        WHEN 0 THEN -1
                        WHEN 1 THEN 1 
                        ELSE 0 
                    END * API2.ItemUnitWeight) 
                FROM @mt_API AS API2
                    WHERE API2.ID <= API1.ID
                ) 

                    -

                    --select 
                    --  case ISNULL(SUM([ProductItemWeight]), 0)
                    --      when 0 then 0
                    --      else SUM([ProductItemWeight])
                    --  end  
                    --from [ExplosiveTracking].[Production].[TransfertHistory]
                    --where stuff(convert(varchar(20),TransfertDateTime,120),17,6,'') < stuff(convert(varchar(20),API1.ASDATE,120),17,6,'')
                (   
                    **MERGE #tempTransfert AS T
                        USING (select 
                            case ISNULL(SUM([ProductItemWeight]) , 0)
                            when 0 then 0 
                            else SUM([ProductItemWeight]) 
                            end  
                            , ID 
                            from [ExplosiveTracking].[Production].[TransfertHistory]
                            where stuff(convert(varchar(20),TransfertDateTime,120),17,6,'') < stuff(convert(varchar(20),API1.ASDATE,120),17,6,'')
                            Group by ID
                            ) as S ([ProductItemWeight],ID)

                        ON (T.ID = S.ID)
                        WHEN MATCHED  
                            THEN DELETE;
                )**
            ) AS ItemWeightBal

        FROM @mt_API  AS API1 
    END

MERGE部分假设首先在DateTime范围内返回ItemWeight的SUM,然后当读取这些记录时,我需要从#tempTransfert表中删除它们,否则,在下一个循环中它将再次读取所有记录< / p>

知道它可能是什么语法错误吗?

感谢您的帮助 此致

0 个答案:

没有答案