Search code examples
sqlsql-serversql-server-2017

How to update Table 1 from multiple other tables when they have nothing in common?


I have a main table and 3 other tables. Each of these tables has a single row only. I would like to update columns of TableMain with corresponding columns from other tables. And these tables don't have any columns that I can join.

create table TableMain(a1 int, a2 int, b1 int, b2 int, c1 int, c2 int)
create table TableA(a1 int, a2 int)
create table TableB(b1 int, b2 int)
create table TableC(c1 int, c2 int)

I have the following, which works, but looks horrible:

update TableMain
set a1 = (select a1 from TableA),
    a2 = (select a2 from TableA),
    b1 = (select b1 from TableB),
    b2 = (select b2 from TableB),
    c1 = (select c1 from TableC),
    c2 = (select c2 from TableC)

I've tried the code below but I am getting NULLs, so this approach doesn't work:

update TableMain
set a1 = ta.a1, a2 = ta.a2, 
    b1 = tb.b1, b2 = tb.b2, 
    c1 = tc.c1, c2 = tc.c2, 
from TableA ta, TableB tb, TableC tc

Is there a more elegant way to update these columns?

P.S. I asked a similar question, but it addressed updating from a single table.


Solution

  • Consider:

    UPDATE tm
    SET tm.a1 = ta.a1,
        tm.a2 = ta.a2, 
        tm.b1 = tb.b1, 
        tm.b2 = tb.b2, 
        tm.c1 = tc.c1, 
        tm.c2 = tc.c2
    FROM TableMain tm
    CROSS JOIN TableA ta
    CROSS JOIN TableB tb
    CROSS JOIN TableC tc