Welcome to dbFreaks.com!
FAQFAQ    SearchSearch      ProfileProfile    Private MessagesPrivate Messages   Log inLog in

update a table from another table

 
   Database Help (Home) -> Programming RSS
Next:  how to calculate the label 0 backup file size  
Author Message
iccsi

External


Since: May 05, 2011
Posts: 7



(Msg. 1) Posted: Mon Oct 17, 2011 12:49 pm
Post subject: update a table from another table
Archived from groups: microsoft>public>sqlserver>programming (more info?)

I want to update my table 1 from table2 and have following data

table1

MyID MyData1 MyData2
1 A C
2 B C
3 H F


table2

MyID1 MyData3 MyData4

1 G C
2 H C

I want to update table1 all MyData2 are "C" to MyData2 data.
I tried to look the UPDATE statement, but can not find anything to do
the update.


Your help is great appreciated,


iccsi

 >> Stay informed about: update a table from another table 
Back to top
Login to vote
Daigoro

External


Since: Oct 18, 2011
Posts: 1



(Msg. 2) Posted: Tue Oct 18, 2011 5:27 am
Post subject: Re: update a table from another table [Login to view extended thread Info.]
Archived from groups: per prev. post (more info?)

Scriveva iccsi lunedì, 17/10/2011:

> I want to update my table 1 from table2 and have following data
>
> table1
>
> MyID MyData1 MyData2
> 1 A C
> 2 B C
> 3 H F
>
>
> table2
>
> MyID1 MyData3 MyData4
>
> 1 G C
> 2 H C
>
> I want to update table1 all MyData2 are "C" to MyData2 data.
> I tried to look the UPDATE statement, but can not find anything to do
> the update.

I didn't understand the specific update you need; anyway, updating a
table from another table works as follows:
UPDATE table1 SET
fieldTable1 = table2.fieldTable2
FROM table2
WHERE (join condition, e.g., table1.id = table2.fkID)

 >> Stay informed about: update a table from another table 
Back to top
Login to vote
iccsi

External


Since: May 05, 2011
Posts: 7



(Msg. 3) Posted: Tue Oct 18, 2011 10:18 am
Post subject: Re: update a table from another table [Login to view extended thread Info.]
Archived from groups: per prev. post (more info?)

On Oct 18, 4:41 am, Daigoro wrote:
> Scriveva iccsi lunedì, 17/10/2011:
>
>
>
>
>
> > I want to update my table 1 from table2 and have following data
>
> > table1
>
> > MyID MyData1  MyData2
> >   1       A             C
> >   2       B             C
> >   3       H             F
>
> > table2
>
> >  MyID1   MyData3    MyData4
>
> >    1         G              C
> >    2         H               C
>
> > I want to update table1 all MyData2 are "C"   to MyData2 data.
> > I tried to look the UPDATE statement, but can not find anything to do
> > the update.
>
> I didn't understand the specific update you need; anyway, updating a
> table from another table works as follows:
> UPDATE table1 SET
> fieldTable1 = table2.fieldTable2
> FROM table2
> WHERE (join condition, e.g., table1.id = table2.fkID)- Hide quoted text -
>
> - Show quoted text -

Thanks a million for helping,


iccsi
 >> Stay informed about: update a table from another table 
Back to top
Login to vote
Erland Sommarskog2

External


Since: May 30, 2004
Posts: 2061



(Msg. 4) Posted: Tue Oct 18, 2011 5:27 pm
Post subject: Re: update a table from another table [Login to view extended thread Info.]
Archived from groups: per prev. post (more info?)

iccsi ( ) writes:
> I want to update my table 1 from table2 and have following data
>
> table1
>
> MyID MyData1 MyData2
> 1 A C
> 2 B C
> 3 H F
>
>
> table2
>
> MyID1 MyData3 MyData4
>
> 1 G C
> 2 H C
>
> I want to update table1 all MyData2 are "C" to MyData2 data.
> I tried to look the UPDATE statement, but can not find anything to do
> the update.

I've been reading this a couple of times, but the description appears
to be incoherent.

The recommendation is that you post:
1) CREATE TABLE statements for your tables.
2) INSERT statements for your data.
3) The desired result given the sample.
4) A short narrative of the underlying business problme.
5) Which version of SQL Server you are using.

This makes it posible to post a tested solution, and it helps to
clarify what you are looking for.


--
Erland Sommarskog, SQL Server MVP, esquel.RemoveThis@sommarskog.se

Links for SQL Server Books Online:
SQL 2008: http://msdn.microsoft.com/en-us/sqlserver/cc514207.aspx
SQL 2005: http://msdn.microsoft.com/en-us/sqlserver/bb895970.aspx
 >> Stay informed about: update a table from another table 
Back to top
Login to vote
Bob Barrows

External


Since: Jan 05, 2011
Posts: 4



(Msg. 5) Posted: Tue Oct 18, 2011 5:28 pm
Post subject: Re: update a table from another table [Login to view extended thread Info.]
Archived from groups: per prev. post (more info?)

Daigoro wrote:
> Scriveva iccsi lunedì, 17/10/2011:
>
>> I want to update my table 1 from table2 and have following data
>>
>> table1
>>
>> MyID MyData1 MyData2
>> 1 A C
>> 2 B C
>> 3 H F
>>
>>
>> table2
>>
>> MyID1 MyData3 MyData4
>>
>> 1 G C
>> 2 H C
>>
>> I want to update table1 all MyData2 are "C" to MyData2 data.
>> I tried to look the UPDATE statement, but can not find anything to do
>> the update.
>
> I didn't understand the specific update you need; anyway, updating a
> table from another table works as follows:
> UPDATE table1 SET
> fieldTable1 = table2.fieldTable2
> FROM table2
> WHERE (join condition, e.g., table1.id = table2.fkID)

No, that is not correct syntax. Both tables need to be mentioned in the FROM
clause, not just table2.

There are basically two choices for updates involving multiple tables:
subquery and UPDATE...FROM. The latter is frowned upon due to situations
where the result might not be predictable, but is often the better choice
when multiple columns are being updated, as long as precautions are taken to
make the result predictable - see below.

Subquery:
UPDATE table1
set col1=(select col2 from table2 where table1.keycol = table2.keycol)

Make sure the subquery returns a single row for any given keycol value.
Failure to do so will raise an error. If the potential for multiple matching
rows exists, use an aggregate function to guarantee a single row. For
example:
UPDATE table1
set col1=(select max(col2) from table2 where table1.keycol = table2.keycol)

UPDATE...FROM:
UPDATE t1
SET col1=t2.col2
FROM table1 as t1 join table2 as t2 ON t1.keycol=t2.keycol

The difference here is: if there are multiple rows in table2 that meet the
join criterion, no error will be raised - col1 will be set to one of the
col2 values in the matching rows, and there is no way to predict which value
it will be set to if multiple possiblities exist. You can mitigate this in a
similar way by using a derived table that groups by keycol:

UPDATE...FROM:
UPDATE t1
SET col1=t2.col2
FROM table1 as t1 join
(SELECT keycol, max(col2) as col2 FROM table2
group by keycol
) as t2 ON t1.keycol=t2.keycol
 >> Stay informed about: update a table from another table 
Back to top
Login to vote
--CELKO--

External


Since: Jan 11, 2008
Posts: 1089



(Msg. 6) Posted: Tue Oct 18, 2011 7:12 pm
Post subject: Re: update a table from another table [Login to view extended thread Info.]
Archived from groups: per prev. post (more info?)

This should be a MERGE to prevent cardinality problems, but a VIEW
looks better than redundant data.
 >> Stay informed about: update a table from another table 
Back to top
Login to vote
Hugo Kornelis

External


Since: Jan 11, 2008
Posts: 440



(Msg. 7) Posted: Tue Oct 18, 2011 7:26 pm
Post subject: Re: update a table from another table [Login to view extended thread Info.]
Archived from groups: per prev. post (more info?)

On Tue, 18 Oct 2011 17:28:12 -0400, "Bob Barrows"
wrote:

>> I didn't understand the specific update you need; anyway, updating a
>> table from another table works as follows:
>> UPDATE table1 SET
>> fieldTable1 = table2.fieldTable2
>> FROM table2
>> WHERE (join condition, e.g., table1.id = table2.fkID)
>
>No, that is not correct syntax. Both tables need to be mentioned in the FROM
>clause, not just table2.

Hi Bob,

As much as I dislike the syntax, it IS valid, even without the target
of the update in the FROM clause. If you paste the above code in
Management Studi, you'll see that it parses correctly. And if the
WHERE clause succeeds in matching each row in table1 to no more than
one row in table2, it will also execute the update as expected.
--
Hugo Kornelis, SQL Server MVP
My SQL Server blog: http://sqlblog.com/blogs/hugo_kornelis
 >> Stay informed about: update a table from another table 
Back to top
Login to vote
Bob Barrows

External


Since: Oct 27, 2010
Posts: 2



(Msg. 8) Posted: Tue Oct 18, 2011 7:28 pm
Post subject: Re: update a table from another table [Login to view extended thread Info.]
Archived from groups: per prev. post (more info?)

Hugo Kornelis wrote:
> On Tue, 18 Oct 2011 17:28:12 -0400, "Bob Barrows"
> wrote:
>
>>> I didn't understand the specific update you need; anyway, updating a
>>> table from another table works as follows:
>>> UPDATE table1 SET
>>> fieldTable1 = table2.fieldTable2
>>> FROM table2
>>> WHERE (join condition, e.g., table1.id = table2.fkID)
>>
>> No, that is not correct syntax. Both tables need to be mentioned in
>> the FROM clause, not just table2.
>
> Hi Bob,
>
> As much as I dislike the syntax, it IS valid, even without the target
> of the update in the FROM clause. If you paste the above code in
> Management Studi, you'll see that it parses correctly. And if the
> WHERE clause succeeds in matching each row in table1 to no more than
> one row in table2, it will also execute the update as expected.

OK, I remember getting an error at one time from trying something like this.
Something else must have caused the error because I just tried it and you
are, of course, correct. Another case of fuzzy memory playing me false I
guess.
 >> Stay informed about: update a table from another table 
Back to top
Login to vote
--CELKO--

External


Since: Jan 11, 2008
Posts: 1089



(Msg. 9) Posted: Wed Oct 19, 2011 6:59 am
Post subject: Re: update a table from another table [Login to view extended thread Info.]
Archived from groups: per prev. post (more info?)

>> OK, I remember getting an error at one time from trying something like this. <<

/*
DROP TABLE OrderDetails, Orders;
CREATE TABLE Orders
(order_nbr INTEGER NOT NULL PRIMARY KEY,
some_col DECIMAL (9,2) NOT NULL);

INSERT INTO Orders VALUES (1, 0);
INSERT INTO Orders VALUES (2, 0);
INSERT INTO Orders VALUES (3, 0);

CREATE TABLE OrderDetails
(order_nbr INTEGER NOT NULL,
sku INTEGER NOT NULL,
item_price DECIMAL (9,2) NOT NULL,
PRIMARY KEY(order_nbr, sku),
-- FOREIGN KEY(sku) REFERENCES Products(sku)
FOREIGN KEY(order_nbr) REFERENCES Orders(order_nbr));

INSERT INTO OrderDetails VALUES (1, 1, 500.00);
INSERT INTO OrderDetails VALUES (1, 2, 205.00);
INSERT INTO OrderDetails VALUES (2, 1, 490.95);
INSERT INTO OrderDetails VALUES (3, 1, 480.00);

SELECT * FROM Orders;

UPDATE Orders
SET Orders.some_col = OrderDetails.item_price
FROM Orders
INNER JOIN
OrderDetails
ON Orders.order_nbr = OrderDetails.order_nbr;

results -- see item #1; last physical value
1 205.00 - where is the $500.00?
2 490.95
3 480.00
*/


--repeat with new physical ordering
DELETE FROM OrderDetails;
DELETE FROM Orders;
DROP INDEX OrderDetails.foobar;

-- index will change the execution plan
CREATE INDEX foobar ON OrderDetails (order_nbr, item_price);

INSERT INTO Orders VALUES (1, 0);
INSERT INTO Orders VALUES (2, 0);
INSERT INTO Orders VALUES (3, 0);

INSERT INTO OrderDetails VALUES (1, 2, 205.00);
INSERT INTO OrderDetails VALUES (1, 1, 500.00);
INSERT INTO OrderDetails VALUES (2, 1, 490.95);
INSERT INTO OrderDetails VALUES (3, 1, 480.00);

UPDATE Orders
SET Orders.some_col = OrderDetails.item_price
FROM Orders
INNER JOIN
OrderDetails
ON Orders.order_nbr = OrderDetails.order_nbr;

SELECT * FROM Orders;

/*
Results
1 500.00
2 490.95
3 480.00
*/

What is the first property that you must have in an INDEX? It cannot
change the results of a statement, only the performance. See the
problem?

This would not have happened with the ANSI syntax. That's the point
that I am trying to make. The ANSI equivalent of the incorrect query
above is

UPDATE Orders -- no alias allowed!
SET some_col
= (SELECT item_price
FROM OrderDetails
WHERE OrderDetails.order_nbr = Orders.order_nbr)
WHERE EXISTS
(SELECT *
FROM OrderDetails
WHERE OrderDetails.order_nbr = Orders.order_nbr);

This will of course result in an error, and even the most junior of
junior programmers will eventually figure out (probably by asking a
senior) what's wrong. At that point, either the query is corrected to
match the request, or a note is sent back to management asking for a
clarification of the ambiguity in the request.

Bottom line: UPDATE FROM *can* be safely used - but only if you are
FOREVER certain that no single row in the target table can EVER be
joined to more than one row in the source table(s); FOREVER in the
ENTIRE LIFETIME of the application; FOREVER across all programmers yet
to come.

I like to err on the safe side, I do not bet only an endless stream of
100% perfect programmers. Use MERGE and get a cardianlity violation
error.
 >> Stay informed about: update a table from another table 
Back to top
Login to vote
Display posts from previous:   
Related Topics:
Update table from same table - Given the following table, I need to update the marketvalue of all '2007-04-30' perfdates that are 0 or null with the marketvalue from '2007-05-31' provided its not 0 or null. What is the best way to write this update? CREATE TABLE [CompositeExtract]...

Last Update on a Table - How can one determine the date when rows have been updated, deleted, or inserted into a table? I have tried sys.objects and sys.tables but modify_date in these tables only reflect a change in table structure and not data rows. Any help would be..

UPDATE using another table - This is not executable SQL, just a way of desribing what I am seeking to achieve: UPDATE mytable set (field1, field2) = (select field1, field2 from #anothertable where mytable.x = #anothertable.x) Is there a way to construct this SQL statement? I..

update trigger on a table - Hi I have a table where two fields together is unik id. On the table I have a update trigger that is updating a date field. The trigger goes like this: Update table1 set date1 = getdate() where id1= (select id1 from inserted) and id2=(select id2 from..

VLDB Table Update - Hope this is the right forum for this question. I have a large table (200M+ records) that I need to run an update query against. The query will replace a value in one of the fields, with a new value derived from another small table (5000 records)..
   Database Help (Home) -> Programming All times are: Pacific Time (US & Canada)
Page 1 of 1

 
You can post new topics in this forum
You can reply to topics in this forum
You can edit your posts in this forum
You can delete your posts in this forum
You can vote in polls in this forum



[ Contact us | Terms of Service/Privacy Policy ]