SQL Join嵌套IF

时间:2016-08-26 10:29:03

标签: sql if-statement nested sql-server-2016

我试图编写一个查询,检查交易中的某个条件,然后如果满足该条件,它将对相关交易进行计算,以确定数量是否为0。 / p>

这个想法是在每个批次中创建了许多交易,当清空时,这些交易在结束时都应该等于0。目标是检查批次是否在前10分钟内标记为已完成,然后进行计算以验证该特定批次的数量是否为零。

我写了下面的内容试图完成这个:

 IF EXISTS(
SELECT DISTINCT
    T0.[ItemCode],
    T0.[ItemName],
    T0.[DocDate],
    CAST(CAST(T0.[CreateTime] / 100 AS varchar) + ':' + CAST(T0.[CreateTime] % 100 AS varchar) AS time) AS [CreateTime],
    T0.[DocType],
    T0.[DocEntry], 
    T0.[DocNum],
    T0.[LocCode],
    T4.[DistNumber] AS [BatchNumber], 
    T1.[Quantity],
    T5.[CalcPrice] AS [Price], 
    T3.[U_ORC_BE_Variance]

FROM OITL T0  
    INNER JOIN ITL1 T1 ON T1.[LogEntry] = T0.[LogEntry]   
    INNER JOIN OITM T2 ON T2.[ItemCode] = T0.[ItemCode]
    INNER JOIN IGE1 T3 ON T3.[DocEntry] = T0.[DocEntry] 
    INNER JOIN OBTN T4 ON T1.[MdAbsEntry] = T4.[AbsEntry]     
    INNER JOIN OINM T5 ON T0.[ItemCode] = T5.[ItemCode] AND T0.[LocCode] = T5.[Warehouse]  AND T0.[AppDocNum] = T5.[BASE_REF]

WHERE T0.[ItemCode] LIKE 'BB%' 
--BBT items only
    AND T3.[U_ORC_BE_Variance] = 'M3'
--Code issued upon BBT empty
    AND CAST(CAST(T0.[CreateTime] / 100 AS varchar) + ':' + CAST(T0.[CreateTime] % 100 AS varchar) AS time) 
        BETWEEN CAST(DATEADD(MINUTE,-10,GETDATE())AS TIME) AND CONVERT(varchar(10), GETDATE(), 108)
--Last 10 minutes
    AND T0.[DocDate] = CAST(LEFT(GETDATE(), 11) AS DATETIME)
--Today
  )


BEGIN

IF(
    (SELECT SUM([Quantity]) FROM ITL1 ) <> '0'
  )

BEGIN
    SELECT 'ALERT'
END

END

我现在需要做的是确保第二个IF(可以调用ALERT)只检查相关的[BatchNumber],这会将事务联系在一起。

我原本以为我可以尝试将第一个IF加入到第二个但是我不确定那会产生我之后的结果吗?如果我这样做,它似乎也会变得非常混乱。

非常感谢。

0 个答案:

没有答案