Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

SQL Window function in update command

Posted on 2013-11-24
2
Medium Priority
?
362 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 2000 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

NFR key for Veeam Backup for Microsoft Office 365

Veeam is happy to provide a free NFR license (for 1 year, up to 10 users). This license allows for the non‑production use of Veeam Backup for Microsoft Office 365 in your home lab without any feature limitations.

Question has a verified solution.

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

After restoring a Microsoft SQL Server database (.bak) from backup or attaching .mdf file, you may run into "Error '15023' User or role already exists in the current database" when you use the "User Mapping" SQL Management Studio functionality to al…
This article explains how to reset the password of the sa account on a Microsoft SQL Server.  The steps in this article work in SQL 2005, 2008, 2008 R2, 2012, 2014 and 2016.
This video shows how to quickly and easily deploy an email signature for all users in Office 365 and prevent it from being added to replies and forwards. (the resulting signature is applied on the server level in Exchange Online) The email signat…
Integration Management Part 2

971 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