SQLCMD查询 - 在下一个到期日期添加产品(基于采购订单)

时间:2017-03-02 01:34:37

标签: sql sql-server sap sqlcmd sapb1

我正在使用.bat和SQLCMD从我的SQL Server导出数据。

目前,这就是我所拥有的:

SQLCMD -S <server name> -d <database name> -U <username> -P <password> -Q
"set nocount on;
SELECT T0.ItemCode,
       T0.FrgnName,
       (SELECT cast(round(T3.Price,2,1) as decimal(18,2)) 
        FROM ITM1 T3 
        WHERE T3.ItemCode = T0.Itemcode AND T3.[PriceList] = '1'),
       cast(round(T1.Price,2,1) as decimal(18,2)), 
       CASE WHEN T2.OnHand - T2.IsCommited > 10 THEN '10' ELSE '0' END,
       T0.CodeBars 
FROM OITM T0 
INNER JOIN ITM1 T1 ON T0.ItemCode = T1.ItemCode AND T1.[PriceList] = '2' 
INNER JOIN OITW T2 ON T0.ItemCode = T2.ItemCode AND T2.WhsCode = '01. Main' 
WHERE T0.ItemName NOT LIKE '%%DNU%%' 
  AND T0.PrchseItem = 'y' AND T0.FrozenFor = 'n' 
  AND T0.QryGroup2 = 'y' AND T0.QryGroup10 = 'n'"
 -s "," -o "\\serveraddress\stockfile.csv" -h-1 -s"~" -W -w 999

基本上,我需要在stock文件中添加最后一篇文章 - 这是 OPOR 表中最早的 DocDueDate 。可能有多个采购订单使用相同的产品 - 所以我肯定需要能够获取最早的数据。

在SAP和我一直在使用的查询中,有一些我似乎无法在SQLCMD脚本中工作:

ISNULL((SELECT top 1 r1.[DocDueDate] 
        FROM POR1 r 
        INNER JOIN OPOR r1 ON r.DocEntry = r1.DocEntry  
        WHERE r.[LineStatus] = 'O' 
          AND r.[ItemCode] = T0.[ItemCode] 
        ORDER BY r1.[DocDueDate]), 0) AS 'PO Date'

我试图将其插入SQLCMD脚本中,没有任何乐趣。然后我试图剔除AS 'PO DATE',但这没有帮助。

我希望有人可以解释为什么这对我不起作用。

此致 瑞克

1 个答案:

答案 0 :(得分:0)

考虑使用聚合查询将内联子查询迁移到派生表以查找最大日期。这样可以避免逐行运行查询,但只需一次调用即可执行:

SELECT T0.ItemCode,
       T0.FrgnName,
       (SELECT CAST(ROUND(T3.Price,2,1) AS DECIMAL(18,2)) 
        FROM ITM1 T3 
        WHERE T3.ItemCode = T0.Itemcode AND T3.[PriceList] = '1'),
       CAST(ROUND(T1.Price,2,1) AS DECIMAL(18,2)), 
       CASE WHEN T2.OnHand - T2.IsCommited > 10 THEN '10' ELSE '0' END,
       T0.CodeBars,
       ISNULL(D.MaxDocDueDate, 0) AS [PO Date]
FROM OITM T0 
INNER JOIN ITM1 T1 ON T0.ItemCode = T1.ItemCode AND T1.[PriceList] = '2' 
INNER JOIN OITW T2 ON T0.ItemCode = T2.ItemCode AND T2.WhsCode = '01. Main' 
INNER JOIN
   ( SELECT r.[ItemCode], MAX(r1.[DocDueDate]) As MaxDocDueDate
     FROM POR1 r 
     INNER JOIN OPOR r1 ON r.DocEntry = r1.DocEntry  
     WHERE r.[LineStatus] = 'O' 
     GROUP BY r.[ItemCode]
   ) D ON T0.[ItemCode] = D.[ItemCode]
WHERE T0.ItemName NOT LIKE '%%DNU%%' 
  AND T0.PrchseItem = 'y' AND T0.FrozenFor = 'n' 
  AND T0.QryGroup2 = 'y' AND T0.QryGroup10 = 'n'"