是否可以使用sql在update语句中使用MAX?

时间:2021-03-06 22:47:04

i am trying to use the MAX function in sql statement. Here is what i am trying to do: something like this:

我想在sql语句中使用MAX函数。这是我想要做的:这样的事情:

UPDATE MainTable
        SET [Date] = GETDATE()

        where [ID] = Max

I know this is wrong specially where i put the where condition but cannot figure out how to use max and update in the same statement. thanks

我知道这是错误的,特别是我把where条件但是无法弄清楚如何在同一语句中使用max和update。谢谢

3 个解决方案

#1


18  

UPDATE MainTable
   SET [Date] = GETDATE()
 where [ID] = (SELECT MAX([ID]) FROM MainTable)

#2


5  

One way

DECLARE @MaxID INT = (select MAX(id) FROM MainTable)

UPDATE MainTable
        SET [Date] = GETDATE()
        where [ID] = @MaxID

That is SQL 2008 syntax, in 2005 you need to do the declaraion and assignment of the variable in two steps

那就是SQL 2008语法,在2005年你需要分两步完成变量的声明和赋值

You could also use a common table expression

您还可以使用公用表表达式

;WITH cte
AS (
SELECT TOP 1 * FROM MainTable
ORDER BY ID DESC

)

UPDATE cte SET [Date] = GETDATE()

Example you can run

您可以运行的示例

CREATE TABLE testNow(id int)
INSERT testNow VALUES(1)
INSERT testNow VALUES(2)

;WITH cte
AS (
SELECT TOP 1 * FROM testNow
ORDER BY ID DESC

)

-- id with 2 will become 5
UPDATE cte SET ID = 5

SELECT * FROM testNow

Output

1
5

#3


1  

UPDATE MainTable
SET [Date] = GETDATE()
WHERE [ID] = (SELECT MAX(your column) FROM yourtable)

#1


18  

UPDATE MainTable
   SET [Date] = GETDATE()
 where [ID] = (SELECT MAX([ID]) FROM MainTable)

#2


5  

One way

DECLARE @MaxID INT = (select MAX(id) FROM MainTable)

UPDATE MainTable
        SET [Date] = GETDATE()
        where [ID] = @MaxID

That is SQL 2008 syntax, in 2005 you need to do the declaraion and assignment of the variable in two steps

那就是SQL 2008语法,在2005年你需要分两步完成变量的声明和赋值

You could also use a common table expression

您还可以使用公用表表达式

;WITH cte
AS (
SELECT TOP 1 * FROM MainTable
ORDER BY ID DESC

)

UPDATE cte SET [Date] = GETDATE()

Example you can run

您可以运行的示例

CREATE TABLE testNow(id int)
INSERT testNow VALUES(1)
INSERT testNow VALUES(2)

;WITH cte
AS (
SELECT TOP 1 * FROM testNow
ORDER BY ID DESC

)

-- id with 2 will become 5
UPDATE cte SET ID = 5

SELECT * FROM testNow

Output

1
5

#3


1  

UPDATE MainTable
SET [Date] = GETDATE()
WHERE [ID] = (SELECT MAX(your column) FROM yourtable)