i am trying to use the MAX function in sql statement. Here is what i am trying to do: something like this:
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
The UPDATE statement is capable of updating more than one row.
MAX function works with “date” data types as well and it will return the maximum or the latest date from the table.
The Having clause is used only with the Select statement The Having clause can be used only with a Select statement. If you use the Having clause with an update or delete query in SQL, it will not work.
UPDATE MainTable
SET [Date] = GETDATE()
where [ID] = (SELECT MAX([ID]) FROM MainTable)
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
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
UPDATE MainTable
SET [Date] = GETDATE()
WHERE [ID] = (SELECT MAX(your column) FROM yourtable)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With