I need to update on of the varchar fields in a table, but only the record that is the longest varchar (has the most data in it.). I could easily find it with this query:
SELECT TOP(1) options
FROM ForrasReportsRicsiTeszt
ORDER BY LEN(options) DESC
Now I need to update it, but I am quite unexperienced with sql. This is a 2005 ms sql server.
my query for updating:
UPDATE ForrasReportsRicsiTeszt
SET options = REPLICATE(options, 4)
WHERE TOP(1) ORDER BY LEN(options) DESC
This gives me an error to TOP(1) which was quite expected. I just don't know the right way to write this query, how could I get to update only the longest varchar field? The one I've managed to get with my select query. Sadly there is no primary key that I could use in my WHERE.
Any help would be much appreciated!
Best Answer
Using the MAX function you could write the following to obtain the entry with the longest varchar
This can then be combined with an UPDATE statement to give
Alternatively you could use a Common Table Expression (CTE).