我正在尝试在sql语句中使用MAX函数。这是我想要做的: 像这样的东西:
UPDATE MainTable
SET [Date] = GETDATE()
where [ID] = Max
我知道这是错误的,特别是在我放置where条件但无法弄清楚如何在同一语句中使用max和update。感谢
答案 0 :(得分:20)
UPDATE MainTable
SET [Date] = GETDATE()
where [ID] = (SELECT MAX([ID]) FROM MainTable)
答案 1 :(得分:5)
单程
DECLARE @MaxID INT = (select MAX(id) FROM MainTable)
UPDATE MainTable
SET [Date] = GETDATE()
where [ID] = @MaxID
那就是SQL 2008语法,在2005年你需要分两步完成声明的声明和赋值
您还可以使用公用表表达式
;WITH cte
AS (
SELECT TOP 1 * FROM MainTable
ORDER BY ID DESC
)
UPDATE cte SET [Date] = GETDATE()
您可以运行的示例
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
输出
1
5
答案 2 :(得分:1)
UPDATE MainTable
SET [Date] = GETDATE()
WHERE [ID] = (SELECT MAX(your column) FROM yourtable)