Solved

sql update query help

Posted on 2014-03-26
3
253 Views
Last Modified: 2014-03-26
I am in need of help writing an update query.

I have a single table:  [companycitymaster]  
This table contains columns [state], [citycode] and [splc].

I need to update the state = 'QC' rows with the [splc] value where
state = 'PQ' BUT only if the state = 'QC' rows are blank and only where the [citycode] is equal.  

I need to do this update before i delete all the pq's.  

Thanks

See data below.

data
0
Comment
Question by:hougie40
3 Comments
 
LVL 33

Expert Comment

by:ste5an
ID: 39956550
E.g.

UPDATE  O
SET     SPLC = ( SELECT I.SPLC
                 FROM   CompanyCityMaster I
                 WHERE  I.CityCode = O.CityCode
                        AND I.[State] = 'PQ'
               )
FROM    CompanyCityMaster O
WHERE   O.[State] = 'QC'
        AND LEN(RTRIM(COALESCE(O.SPLC, ''))) = 0;

Open in new window

0
 
LVL 69

Accepted Solution

by:
Scott Pletcher earned 500 total points
ID: 39956726
UPDATE ccm_qc
SET splc = ccm_pq.splc
FROM (
    SELECT state, citycode, splc
    FROM companycitymaster
    WHERE
        state = 'QC' AND
        splc = ''
) AS ccm_qc
INNER JOIN (
    SELECT state, citycode, splc
    FROM companycitymaster
    WHERE
        state = 'PQ' AND
        splc > ''
) AS ccm_pq ON
    ccm_pq.citycode = ccm_qc.citycode
0
 

Author Closing Comment

by:hougie40
ID: 39956791
perfect.  I prefer the inner join over the where clause join.

Thanks scott.
0

Featured Post

Ransomware: The New Cyber Threat & How to Stop It

This infographic explains ransomware, type of malware that blocks access to your files or your systems and holds them hostage until a ransom is paid. It also examines the different types of ransomware and explains what you can do to thwart this sinister online threat.  

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…
Ever needed a SQL 2008 Database replicated/mirrored/log shipped on another server but you can't take the downtime inflicted by initial snapshot or disconnect while T-logs are restored or mirror applied? You can use SQL Server Initialize from Backup…
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…

825 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