SQL 服务器 Select 最大程序

SQL SERVER Select MAX Procedure

我正在尝试创建一个程序来更改 table 上的用户登录,但如果我正在尝试的程序是特定 status:Here 中的最后一个条目,则只更改最后一个条目:

Update T_STATUS_CLIC 
SET iEDV = @iEDV 
WHERE 
    iClic = @iClic and iStatus = '9' and dtDateCreated = 
    (select max (dtDateCreated)  FROM T_STATUS_CLIC where iclic = @iClic );

如果 table 最大日期的最后一行在 iStatus 9 中,我只能更改 iEDV,我不知道这是否可能,我正在尝试这样的事情:

iStatus = (select iStatus = '9' where max(dtDateCreated))

但是没有用,有办法吗?

如果我没理解错的话,每个 "iClic" 可以有很多行,如果最近的行的状态为 9,则只想更新行。

如果 table 有真正的 PK 会有所帮助。

但我相信这会奏效,因为:

CREATE TABLE T_STATUS_CLIC (iClic INT , iEDV INT, iStatus CHAR(1), dtDateCreated DateTime)
DECLARE @iEDV int = 123;
DECLARE @iClic int = 8888;

这个脚本:

; -- WITH must be preceeded by a semicolon
WITH clicmax as (SELECT iClic
                ,   max(dtDateCreated) as maxdt 
                ,   max(case when mc.iStatus = '9' THEN mc.dtDateCreated ELSE null END) as Max9dt
                FROM dbo.T_STATUS_CLIC mc WHERE iClic = @iClic GROUP BY iClic)
UPDATE tt
SET iEDV = @iEDV
FROM dbo.T_STATUS_CLIC tt
    JOIN clicmax on clicmax.iClic = tt.iClic 
WHERE tt.iClic = @iClic
and tt.dtDateCreated = clicmax.Max9dt  
and tt.dtDateCreated = clicmax.Maxdt
and tt.iStatus = '9';

WITH 子句确定实际最大日期和状态 9 的最大日期。然后更新可以在其 WHERE 子句中引用这两个。