Link to home
Start Free TrialLog in
Avatar of kojak33
kojak33

asked on

combining fields from one select to update a single field in a separate statement.

i have a stored procedure trying to do the following:

SELECT field1, field2, field3...
FROM tableA
WHERE id = @id

Field1 = 1
Field2 = 0
Field3 = 1
Field4 = 0

If the field has a value of 1 Then I want to add that field # to my input into the next table

UPDATE TableB
SET combinedvalue = @values
WHERE id = @someid

in this case, @values should equal 13  (because both field1 and field3 have values of 1)

Thanks in advance.
ASKER CERTIFIED SOLUTION
Avatar of rafrancisco
rafrancisco

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of obahat
obahat

Good answer, however you can do this in a single statement. No need to store the variables, assuming the the IDs are common.

UPDATE b
SET combinedvalue = ISNULL(CAST(a.Field1*1 AS VARCHAR), '')
        + ISNULL(CAST(a.Field1*2 AS VARCHAR), '')
        + ISNULL(CAST(a.Field1*3 AS VARCHAR), '')
        + ...
FROM TableB b
        INNER JOIN TableA a
        ON a.ID = b.ID
WHERE a.ID = @CommonID