Solved

SQL Window function in update command

Posted on 2013-11-24
2
344 Views
Last Modified: 2013-11-24
I am trying to solve a unique document number issue. I need to prefix the REFERNCE field with a row number value. However, when I run this I get the error below. How do I solve this?

UPDATE MYTABLE
SET REFERNCE=RIGHT('000',3-LEN(RTRIM(CONVERT(CHAR(3),ROW_NUMBER() OVER(ORDER BY REFERNCE)))))+RTRIM(CONVERT(CHAR(3),ROW_NUMBER() OVER(ORDER BY REFERNCE)))
WHERE REFERNCE LIKE 'POST-PPD-5092%'

Windowed functions can only appear in SELECT or ORDER BY  clauses
0
Comment
Question by:rwheeler23
2 Comments
 
LVL 5

Accepted Solution

by:
Lawrence Barnes earned 500 total points
ID: 39673207
Looks like you are trying to update with a value that does not exist yet.  I would rewrite it like this...but unable to test at the moment since I am at a swim meet.


UPDATE t1
SET t1.REFERNCE = t3.AdjReference
FROM MYTABLE t1
INNER JOIN (
SELECT t2.REFERENCE, AdjReference = RIGHT('000',3-LEN(RTRIM(CONVERT(CHAR(3),ROW_NUMBER() OVER(ORDER BY t2.REFERNCE)))))+RTRIM(CONVERT(CHAR(3),ROW_NUMBER() OVER(ORDER BY t2.REFERNCE)))
FROM MYTABLE t2
WHERE t2.REFERNCE LIKE 'POST-PPD-5092%' ) t3 ON t1.REFERENCE = t3.REFERENCE
0
 

Author Closing Comment

by:rwheeler23
ID: 39673373
Perhaps I should take up swimming. Your answer was perfect. Thank you!
0

Featured Post

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Long way back, we had to take help from third party tools in order to encrypt and decrypt data.  Gradually Microsoft understood the need for this feature and started to implement it by building functionality into SQL Server. Finally, with SQL 2008, …
Naughty Me. While I was changing the database name from DB1 to DB_PROD1 (yep it's not real database name ^v^), I changed the database name and notified my application fellows that I did it. They turn on the application, and everything is working. A …
Although Jacob Bernoulli (1654-1705) has been credited as the creator of "Binomial Distribution Table", Gottfried Leibniz (1646-1716) did his dissertation on the subject in 1666; Leibniz you may recall is the co-inventor of "Calculus" and beat Isaac…

828 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question