SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Update table by grabbing data from other table
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

theKid27
Starting Member

21 Posts

Posted - 03/20/2013 :  02:21:13  Show Profile  Reply with Quote
Hi Experts/Members,

I have a table that I would like to update I'll call it Table A and Table B.

Table A

CarType Color
------------------
Car 1 NULL
Car 2 NULL
Car 3 NULL

Table B

CarType Color
------------------
Car 1 Red
Car 2 Blue
Car 3 Green

I would like to write an update statement to update in Table A, which will then become like the below.


CarType Color
------------------
Car 1 Red
Car 2 Blue
Car 3 Green


I have tried a very manual way which i find it very hard to do it as i will have to do write it for each color.. my statement is as below:

UPDATE Table A
SET Table A.[Color]='Red'
Where Table A.[CarType] In (SELECT [CarType] FROM Table B)

Hope that you all can advice.. Appreciate for the help

Thanks




ahmeds08
Aged Yak Warrior

India
655 Posts

Posted - 03/20/2013 :  03:16:54  Show Profile  Send ahmeds08 a Yahoo! Message  Reply with Quote
try this

update tablea a set a.color=b.color
inner join tableb b
on a.cartype=b.cartype
Go to Top of Page

bandi
Flowing Fount of Yak Knowledge

India
2217 Posts

Posted - 03/20/2013 :  03:20:29  Show Profile  Reply with Quote

CREATE Table A (CarType VARCHAR(10), Color varchar(10))
INSERT INTO A 
SELECT 'Car 1', NULL UNION ALL
SELECT 'Car 2', NULL UNION ALL
SELECT 'Car 3', NULL 

CREATE Table B (CarType VARCHAR(10), Color varchar(10))
INSERT INTO B
SELECT 'Car 1', 'Red' union all
SELECT 'Car 2', 'Blue' union all
SELECT 'Car 3', 'Green'

--Try this
Update A
SET a.Color = b.Color
FROM A 
JOIN B ON a.CarType = b.CarType

SELECT * FROM A


--
Chandu
Go to Top of Page

theKid27
Starting Member

21 Posts

Posted - 03/20/2013 :  05:28:16  Show Profile  Reply with Quote
Thanks all.. it works
Go to Top of Page

bandi
Flowing Fount of Yak Knowledge

India
2217 Posts

Posted - 03/20/2013 :  05:40:06  Show Profile  Reply with Quote
quote:
Originally posted by theKid27

Thanks all.. it works


Welcome

--
Chandu
Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.05 seconds. Powered By: Snitz Forums 2000