Jon Finstad
Jon Finstad

Reputation: 11

Conditional field replacement in tsql

I am trying to take some data like:

Col1 | Col2 | Col3 | Col4
-------------------------
One  | Two  | NULL | Foo
Two  | Bar  | Baz  | NULL

And I want to recognize if there's a null or not. Like, as in, if there is not a NULL in Col4 for that particular line, to replace the value in Col2 with Col4. So, it would come out like:

Col1 | Col2 | Col3 | Col4
-------------------------
One  | Foo  | NULL | Foo
Two  | Bar  | Baz  | NULL

I can get as far as coming up with the "subroutine" for the action, but I am having trouble just making it work conditionally.

This is what I have so far:

update dbo.Table 
    set dbo.Table.First_Name=dbo.Table.ZV_First_Name
    from dbo.Table
         join dbo.Table
         on
            (dbo.Table.First_Name=dbo.Table.ZV_First_Name);

But, I think I am way off with this.

Any help would be really appreciated.

Thank you all.

Upvotes: 1

Views: 42

Answers (2)

Gordon Linoff
Gordon Linoff

Reputation: 1269463

Based on your original question:

update t
    set col2 = col4
    where col4 is not null;

I'm not quite sure how your proposed query fits in.

Upvotes: 2

ScaisEdge
ScaisEdge

Reputation: 133360

you should use the where clause eg:

update dbo.Table 
set dbo.Table.First_Name=dbo.Table.ZV_First_Name
where dbo.Table.ZV_First_Name is not null

Upvotes: 0

Related Questions