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

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 728
  • Last Modified:

Change a field value within Update Select

I'm wondering if I can combine the following two queries to run as one query.  The first query is an Insert/select:  The second query is an update based on one of the fields being inserted.  The field is StatusCode.  It gets inserted with an initial value of 1 but then it needs to be changed based on the values of some other fields in the query.  Is it possible to do this all in one query?  

----- 1st query

insert into FileOne
    (CNumber,
    ID,
    DCode,
    PCode,
    b.Indicator,
    b.Discount,
    StatusCode)
SELECT
    cast(a.CNumber as char (5)),
    cast(a.ID as varchar (16)),
    cast(a.DCode as varchar (5)),
    b.PCode,
    b.Indicator,
    b.Discount,
    1
FROM PFILE a
    INNER JOIN TFile b
        ON a.ID = b.ID
WHERE SUBSTRING(b.CNumber,1,1)<>'S'

---- 2nd query

UPDATE FileOne
SET StatusCode = 0
WHERE
 (indicator = 0
OR Pcode <> 'D'
OR Dcode <>'C'
OR discount = 1)
0
dkcoop03
Asked:
dkcoop03
1 Solution
 
chapmandewCommented:
No, you cannot.  In 2008, a MERGE statement can do something similar to what you're doing, but for right now you have to use seperate statements....INSERT and UPDATE are distinct operations.
0
 
rickchildCommented:
Try this:
insert into FileOne
    (CNumber,
    ID,
    DCode,
    PCode,
    b.Indicator,
    b.Discount,
    StatusCode) 
SELECT
    cast(a.CNumber as char (5)),
    cast(a.ID as varchar (16)),
    cast(a.DCode as varchar (5)),
    b.PCode,
    b.Indicator,
    b.Discount,
    CASE
        WHEN (b.indicator = 0 OR b.Pcode <> 'D' OR cast(a.Dcode as varchar(5)) <>'C' OR discount = 1) THEN 0
    ELSE 1
    END as StatusCode
FROM PFILE a
    INNER JOIN TFile b
        ON a.ID = b.ID
WHERE SUBSTRING(b.CNumber,1,1)<>'S'

Open in new window

0
 
dkcoop03Author Commented:
Thanks, that works great!
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now