2

我有一个返回 DISTINCT ID 的 CTE。我想对每个返回的 Id 执行一个标量函数。

WITH cte (reqID) as 

(SELECT DISTINCT pol.ReqID FROM 
LOG_PackingListItems pli
JOIN
v_PO_LN              pol on pol.PO_ID  = pli.PoId
WHERE  
pli.PackingListHeaderID = 1)


EXEC dbo.spUpdateLOG_ReqCompleteCheck  reqID -- Error "Incorrect Syntax near EXEC"

EXEC 行是我想要做的,但我得到一个语法错误。不确定我想做的事情是否可行,或者我是否确实有语法错误。有任何想法吗?

编辑: 我正在添加存储过程的代码,因为我现在使用 realnumber3012 建议的表值参数

编辑: 我已经更改了我的 CTE 代码,因此它按照 realnumber 的建议填充了表格类型。现在执行 spUpdateLOG_ReqCompleteCheck “子查询返回多个值”时出现错误。

DECLARE @ReqIdTVP as ReqIdType;
DELETE FROM @ReqIDTVP;
with cte (reqID) as 
(select distinct pol.ReqID from 
 LOG_PackingListItems pli
 join
 v_PO_LN    pol on pol.PO_ID  = pli.PoId
 where 
  pli.PackingListHeaderID = @PackingListHeaderID)

INSERT INTO @ReqIdTVP 
SELECT * FROM cte

EXEC dbo.spUpdateLOG_ReqCompleteCheck @ReqIdTVP

存储过程代码:

Alter PROCEDURE spUpdateLOG_ReqCompleteCheck

(@ReqIdTVP ReqIdType READONLY )  

AS 
BEGIN

DECLARE @TotalOrd int
DECLARE @TotalRx int
DECLARE @ReqID char(8)  

SET @ReqID = (SELECT  ReqID FROM @ReqIdTVP)

SET @TotalOrd = (SELECT ISNULL(SUM(ORD_QTY),0)
            FROM        dbo.v_PoLnNonFreight  l
            WHERE l.ReqID = @reqID)


SET @TotalRx = (SELECT  ISNULL(SUM(TotalRxSite),0)
            FROM        dbo.v_PoLnNonFreight  l
            WHERE l.ReqID = @reqID)


IF @TotalRx >=  @TotalOrd
 BEGIN
  DECLARE @curDate datetime
  SET @CurDate = ISNULL(@CurDate,GetDate()) 
SET NOCOUNT ON;

  UPDATE LOG_ReqHeader   
  SET 
ReqCompleteDate   = @curDate,
ReqStatus = 'Complete'

  WHERE ReqID = @ReqID  
 END
END
4

1 回答 1

0

似乎您的存储过程唯一要做的就是更新日志记录表:(它仅通过此语句更改状态并且不返回任何内容????

UPDATE LOG_ReqHeader   
  SET 
ReqCompleteDate   = @curDate,
ReqStatus = 'Complete'

  WHERE ReqID = @ReqID 

如何将逻辑拆分并编写一个函数(如果可能的话,内联将评估您正在寻找的条件(并不真正了解您在那里做什么) - 在 CTE 的结果上运行该函数(将其包装在如果需要,可以使用另一个 CTE)与 CROSS APPLY OPERATOR。

您最终会得到一个类似于 [ReqId]、[UpdateLog] 的结果集(其中 updateLog 是一个 BIT)

然后只需对结果进行基于集合的更新:

UPDATE l SET
    ReqCompleteDate   = @curDate,
    ReqStatus = 'Complete'
FROM
    LOG_ReqHeader AS l
    JOIN <CTE> AS c ON c.[ReqID] = l.[ReqID]
WHERE
    c.[UpdateLog] = 0x1

这有道理吗?

于 2013-04-25T21:52:13.897 回答