Solved

SQL update query syntax - SQL 2008 R2

Posted on 2014-02-20
3
364 Views
Last Modified: 2014-02-20
Hi experts,

In the data here, SAMPLE_ID_ALT needs to be updated to what I have typed in.  For every 'NS' in the SAMPLE_ID column, the SAMPLE_ID_ALT needs to be set incrementally to NS_001, NS_002 and start again when a new SITE_ID is found.  

I have tried this, and can see why the optimizer might not like it, but I cannot find a workaround.  Can anyone help please?  I would rather not use cursors if I can help it.

UPDATE GB_CB_LITH
SET SAMPLE_ID_ALT = 'NS_'+ RIGHT('000'+CAST(ROW_NUMBER()
                               OVER (PARTITION BY SITE_ID
                                     ORDER BY DEPTH_FROM)
               AS VARCHAR(3)),3)
  WHERE SAMPLE_ID = 'NS'
TEMP-LITH-DATA2.xlsx
0
Comment
Question by:colinspurs
  • 2
3 Comments
 
LVL 16

Accepted Solution

by:
Surendra Nath earned 500 total points
ID: 39873308
try this out

;WITH C AS
(
SELECT RIGHT('000'+CAST(ROW_NUMBER() OVER (PARTITION BY SITE_ID ORDER BY DEPTH_FROM) AS VARCHAR(3)),3) RN,* FROM GB_CB_LITH WHERE G.SAMPLE_ID = 'NS' 
)

UPDATE G
SET SAMPLE_ID_ALT = 'NS_'+ RN
FROM GB_CB_LITH G
JOIN C 
ON G.<PK> = C.<PK>
WHERE G.SAMPLE_ID = 'NS' 


--NOTE in the above you have to replace the PK with the primary keys

Open in new window

0
 
LVL 3

Author Comment

by:colinspurs
ID: 39873398
Superb!  Thanks.

I think you meant GB_CB_LITH G WHERE G.SAMPLE_ID = 'NS'  in line 3.
                                                  =
0
 
LVL 3

Author Closing Comment

by:colinspurs
ID: 39873400
Brilliant, thanks a lot.
0

Featured Post

NAS Cloud Backup Strategies

This article explains backup scenarios when using network storage. We review the so-called “3-2-1 strategy” and summarize the methods you can use to send NAS data to the cloud

Question has a verified solution.

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

In this article I will describe the Backup & Restore method as one possible migration process and I will add the extra tasks needed for an upgrade when and where is applied so it will cover all.
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.
Via a live example, show how to backup a database, simulate a failure backup the tail of the database transaction log and perform the restore.
Using examples as well as descriptions, and references to Books Online, show the documentation available for datatypes, explain the available data types and show how data can be passed into and out of variables.

816 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

Need Help in Real-Time?

Connect with top rated Experts

7 Experts available now in Live!

Get 1:1 Help Now