Solved

SQL update query syntax - SQL 2008 R2

Posted on 2014-02-20
3
359 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

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

If you have heard of RFC822 date formats, they can be quite a challenge in SQL Server. RFC822 is an Internet standard format for email message headers, including all dates within those headers. The RFC822 protocols are available in detail at:   ht…
Load balancing is the method of dividing the total amount of work performed by one computer between two or more computers. Its aim is to get more work done in the same amount of time, ensuring that all the users get served faster.
Via a live example, show how to extract information from SQL Server on Database, Connection and Server properties
Via a live example, show how to shrink a transaction log file down to a reasonable size.

760 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

19 Experts available now in Live!

Get 1:1 Help Now