Solved

MS SQL Multi Joins Update/Select

Posted on 2015-01-16
3
85 Views
Last Modified: 2015-01-18
Hi,
I have 3 tables structured as follows
table1 (equipnum, field1, field2)  (this table is used for reporting
table2 (projectID, equipnum, field11, field21)
table3 (projectID, equipnum, field111, field211)

I want to update table1 with values from table2 and table3
The join key table1-table2 : equipnum, table2-table3: projectID, equipnum

Regards
0
Comment
Question by:Omer-Pitou
3 Comments
 
LVL 143

Expert Comment

by:Guy Hengel [angelIII / a3]
ID: 40554884
0
 
LVL 15

Expert Comment

by:Vikas Garg
ID: 40554924
Hello,

You can try something like this

UPDATE Table1
SET Col2 = t2.Col2,
Col3 = t2.Col3
FROM Table1 t1
INNER JOIN Table2 t2 ON t1.Col1 = t2.Col1
WHERE t1.Col1 IN (21, 31)
GO

Open in new window

0
 
LVL 13

Accepted Solution

by:
Nakul Vachhrajani earned 500 total points
ID: 40556436
@Vikas: Your solution will work, only catch is that using UPDATE Table1.... FROM Table1 t1 may cause the table to block itself in an environment that supports parallelism. A better alternate is to use UPDATE t1....FROM Table1 t1 as shown below:

UPDATE t1
SET t1.field1 = t2.field11 - field111,
    t1.field2 = t2.field21 - field211
FROM dbo.table1 AS t1
INNER JOIN dbo.table2 AS t2 ON t1.equipnum = t2.equipnum
INNER JOIN dbo.table3 AS t3 ON t2.projectID = t3.projectID
                           AND t2.equipnum = t3.equipnum;

Open in new window

0

Featured Post

Efficient way to get backups off site to Azure

This user guide provides instructions on how to deploy and configure both a StoneFly Scale Out NAS Enterprise Cloud Drive virtual machine and Veeam Cloud Connect in the Microsoft Azure Cloud.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article explains how to reset the password of the sa account on a Microsoft SQL Server.  The steps in this article work in SQL 2005, 2008, 2008 R2, 2012, 2014 and 2016.
JSON is being used more and more, besides XML, and you surely wanted to parse the data out into SQL instead of doing it in some Javascript. The below function in SQL Server can do the job for you, returning a quick table with the parsed data.
This video shows, step by step, how to configure Oracle Heterogeneous Services via the Generic Gateway Agent in order to make a connection from an Oracle session and access a remote SQL Server database table.
This videos aims to give the viewer a basic demonstration of how a user can query current session information by using the SYS_CONTEXT function

735 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question