D. Sag
D. Sag

Reputation: 13

T-SQL Updating Query

I'm new to SQL and I'm trying to figure out how to SUM several columns and update an existing column with 1 or 0 if the SUM of the columns is more than 0. Also, making sure null values get assigned a 0 value.

How to do something like the following in T-SQL?

if (select (coalesce(COL1, 0) +
coalesce(COL2 0) +
coalesce(COL3, 0) +
coalesce(COL4, 0) +
coalesce(COL5, 0) from SOMETABLE where X_CONDITION = 10)  >  0)
update SOMETABLE set ABC_COLUMN = 1
    else
    set ABC_COLUMN = 0;

EDIT:

Currently the table looks somewhat like this:

x_condition | col1 | col2 |col3| col4| col5| abc_column
------------| -----| -----| ---| ----|-----|-----------
     7      | 1    |      |    |     |     |    0  (this in incorrect)
     7      | 0    |   0  |    |  0  |     |    0  (this is correct)
     5      | 1    |   1  |    |     |     |    0  (this is incorrect)

I want the abc_column fixed - almost like a flag:

 x_condition | col1 | col2 |col3| col4| col5| abc_column
------------| -----| -----| ---| ----|-----|-----------
     7      | 1    |      |    |     |     |    1
     7      | 0    |   0  |    |  0  |     |    0
     5      | 1    |   1  |    |     |     |    1

Thank you!

Upvotes: 1

Views: 104

Answers (2)

Mansoor
Mansoor

Reputation: 4192

Use UPDATE statement as below format :

  UPDATE SOMETABLE
  SET ABC_COLUMN = CASE WHEN ISNULL(COL1,0) > 0 THEN 1
                        WHEN ISNULL(COL2,0) > 0 THEN 1
                        WHEN ISNULL(COL3,0) > 0 THEN 1
                        WHEN ISNULL(COL4,0) > 0 THEN 1
                        WHEN ISNULL(COL5,0) > 0 THEN 1 ELSE 0 END 

Upvotes: 1

Gordon Linoff
Gordon Linoff

Reputation: 1269553

This sounds like an update statement with some arithmetic:

update SOMETABLE
    set ABC_COLUMN = (case when coalesce(COL1, 0) + coalesce(COL2 0) +
                                coalesce(COL3, 0) + coalesce(COL4, 0) +
                                coalesce(COL5, 0) > 0
                           then 1 else 0
                      end);

You pretty much have all the pieces in your query.

Upvotes: 1

Related Questions