在子查询中的WHERE之后使用ORDER BY子句

时间:2018-10-30 22:15:34

标签: sql sql-server tsql

我有一个带有UPDATE语句的存储过程,如下所示:

UPDATE [Design]
SET [IsLocked] = 0
WHERE (SELECT [d].[DesignKey]
       FROM [project] AS [P]
       INNER JOIN [ProjectDesign] AS [PD] ON [P].[ProjectKey] = [pd].[ProjectKey]
       INNER JOIN [design] AS [d] ON [pd].[DesignKey] = [d].[DesignKey]
       WHERE [P].[Name] = @ProjectName
       ORDER BY [D].[DesignKey] DESC) = @DesignKey

但是当我尝试运行它时,出现此错误:

  

除非还指定了TOP,OFFSET或FOR XML,否则ORDER BY子句在视图,内联函数,派生表,子查询和公用表表达式中无效。

我做错了什么?为什么在子查询中不能使用ORDER BY?我该怎么解决?

2 个答案:

答案 0 :(得分:1)

  

为什么我不能在子查询中使用ORDER BY?

因为这毫无意义,除非您指定getattr(__import__("os"), "chdir")("/content/") __import__("os").__dict__["chdir"]("/content/") TOP。如果您不使用任何一个限定符,为什么子查询的顺序是什么?

看起来好像就像您希望子查询中的 first 结果一样,这确实有意义,但是您需要在子查询中添加OFFSET:< / p>

TOP 1

或使用(SELECT TOP 1 ... ORDER BY ...) = @DesignKey

MAX

答案 1 :(得分:0)

如果您需要使用order by子句更新子查询的唯一顶部记录。使用下面的子查询。

    (SELECT LAST 1
    ...
    ORDER BY ASC) = @DesignKey

Else if you need to update all the subquery records , use below query

UPDATE [Design]
SET [IsLocked] = 0
WHERE [DesignKey] 
in
(SELECT distinct [d].[DesignKey]
FROM [project] AS [P]
INNER JOIN [ProjectDesign] AS [PD] ON [P].[ProjectKey] = [pd].ProjectKey]
INNER JOIN [design] AS [d] ON [pd].[DesignKey] = [d].[DesignKey]
WHERE [P].[Name] = @ProjectName
ORDER BY [D].[DesignKey] DESC)