1

I have 2 tables. Both have the same amount of rows.

Sample data:

Table1{
    Id, IdTable2Row
} 

Table2 {
    Id, RedChicken -- LOL
}

Each row of Table1 (column IdTable2Row) should get the id of 1 row of table 2 (irrelevant which one). Table1.IdTable2Row is null in every row before the operation.

How can I do something like this?

UPDATE Table1 SET IdTable2Row = (SELECT Id FROM [Table2])
3
  • 1
    Add some sample table data and the expected result - as formatted text. Commented Jul 7, 2017 at 8:45
  • Can the id repeat? Be specific as to what output is expected? Commented Jul 7, 2017 at 8:48
  • They cannot repeat Commented Jul 7, 2017 at 8:49

3 Answers 3

1
update T1
set idtablerow = t2.id
from Table1 T1
inner join Table2 T2
on T1.something = T2.something

In your case, with no common column:

with T1 as
(
select Table1.*, row_number() over (order by anycolumn) rn
from Table1
)
update T1 
set idtablerow = t2.id
from T1
inner join 
(
select x1.*, row_number() over (order by id) rn
from Table2 x1
) T2
on t1.rn = t2.rn

Should work

Sign up to request clarification or add additional context in comments.

2 Comments

There are no common values to do the join (T1.something = T2.something).
Why the Over() ? I mean, the order is irrelevant.
1

If I understand correctly you need to match rows 1 to 1. Here is a solution I come up with:

declare @Table1 table(
    Id INT, 
    IdTable2Row INT NULL
)

declare @Table2 table(
    Id INT, RedChicken varchar(10) -- LOL
)

INSERT INTO @Table1
    VALUES
    (
        1,NULL
    ),(
        2,NULL
    ),(
        3,NULL
    );

INSERT INTO @Table2
    VALUES
    (
        10,'s'
    ),(
        20,'a'
    ),(
        30,'b'
    );


SELECT * 
FROM @Table1 ;
SELECT *
FROM @Table2;


WITH cte1 AS
(
SELECT 
ROW_NUMBER() over(ORDER by Id)  AS rown
,Id
,IdTable2Row
FROM @Table1
),
cte2 AS
(
SELECT ROW_NUMBER() over(ORDER by Id) AS rown
 ,Id
 ,RedChicken
FROM @Table2
)
UPDATE t
SET IdTable2Row = c2.Id
FROM @Table1 t
JOIN cte1 c1 ON c1.Id = t.Id
JOIN cte2 c2 ON c1.rown = c2.rown

SELECT *
FROM @Table1

1 Comment

+1 for declaring RedChicken. Also, the answer seems to be similar to JohnHC's and I got it working already. I will be reading a bit on each step of both answers and documentation to understand exactly how the expected results are obtained! Thanks.
-1

IN SQL SERVER if there is common column then you can join the table and update

update a set a.IdTable2Row=b.Id from 
Table1 a ,Table2 b
where a.column=b.column

1 Comment

There is no common column, except the future Table1.IdTable2Row = Table2.Id

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.