不允许在更新声明中排序

时间:2013-01-22 07:40:11

标签: sql-server-2008-r2 azure-sql-database

我试图根据内部连接条件设置一个标志,我需要在查询中使用order by子句因为我的条件依赖于具有特定字符串的最后一个记录但是它不能是最后一个表,我试过它说这是不允许的,我试过的东西似乎对我不起作用。

首先尝试:


UPDATE TESTINSTANCE SET NETWORKOUTAGE='1' 
WHERE TESTINSTANCEID IN (SELECT DISTINCT A.TESTINSTANCEID FROM AUDITLOG A 
INNER JOIN TESTINSTANCE TI ON TI.TESTINSTANCEID=A.TESTINSTANCEID AND TI.TIMETAKEN IS NULL 
AND TI.NETWORKOUTAGE!='1' 
AND TI.ISSENTTOEDUNXT IS NULL 
WHERE REPLACE(A.MESSAGE, ' ', '')=REPLACE('PING RESPONSE CAME FROM SERVER',' ','')  
AND DATEDIFF (MINUTE, A.REPORTEDTIME,  GETDATE())>=5 ORDER BY A.AUDITID DESC);

第二次尝试


UPDATE TI SET NETWORKOUTAGE='1' 
FROM  TESTINSTANCE TI INNER JOIN (SELECT DISTINCT A.TESTINSTANCEID FROM AUDITLOG A 
INNER JOIN TESTINSTANCE TI ON TI.TESTINSTANCEID=A.TESTINSTANCEID AND TI.TIMETAKEN IS NULL 
AND TI.NETWORKOUTAGE!='1' 
AND TI.ISSENTTOEDUNXT IS NULL 
WHERE REPLACE(A.MESSAGE, ' ', '')=REPLACE('PING RESPONSE CAME FROM SERVER',' ','')  
AND DATEDIFF (MINUTE, A.REPORTEDTIME,  GETDATE())>=5 ORDER BY A.AUDITID DESC) RES ON RES.TESTINSTANCEID=TI.TESTINSTANCEID;

但两个都给了我同样的错误,

The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP or FOR XML is also specified. 

我在这里缺少什么?

1 个答案:

答案 0 :(得分:0)

看到你想要做的事情有点棘手,显然我们没有你的牌桌。但我认为你想要这样的东西:

.... (SELECT A.TESTINSTANCEID,A.REPORTEDTIME,
     ROW_NUMBER() OVER (PARTITION BY A.TESTINSTANCEID ORDER BY A.AUDITID DESC) as RN
...

) RES ON RES.TESTINSTANCEID=TI.TESTINSTANCEID AND
     RES.RN = 1 AND
     DATEDIFF (MINUTE, RES.REPORTEDTIME,  GETDATE())>=5

从子查询中删除日期比较。基本上,将子查询编号设为适当的行,这样,在连接条件下,您可以只选择最新的行并使用REPORTEDTIME值。