Follow sqlserver-dba.com

Subscribe to RSS feed  Follow @jackvamvas - Twitter

*Use the Comments section for questions

SQLServer-DBA.com Links

Dba_db2_button

dba-ninja.com

SQL Server DBA Jobs

T-SQL UPDATE JOIN on a table.

10 June,2011 by Tom Collins

SQL Server T-SQL UPDATE with JOIN on a table – is a simple task. Follow the pattern below .The example below takes values from one table and updates on another table – based on the JOIN between the two columns

 

--create #temp1_guitarists , with missing values on song column

CREATE TABLE #temp1_guitarists

(guitarist_ID INT,

 guitarist_name VARCHAR(50),

 song VARCHAR(50)

);

--create #temp1_guitarists_song  , with songs

CREATE TABLE #temp1_guitarists_song

(guitarist_ID INT,

 song VARCHAR(50)

);

 --insert values

INSERT INTO #temp1_guitarists

SELECT 1,'Joe Satriani',''

UNION

SELECT 2,'Jimi Hendrix',''

UNION

SELECT 3,'Prince','';

 

INSERT INTO #temp1_guitarists_song

SELECT 1,'Satch Boogie'

UNION

SELECT 2,'Red House'

UNION

SELECT 3,'When Doves Cry';

--Now , for the UPDATE statement

UPDATE #temp1_guitarists SET song = B.song

FROM #temp1_guitarists AS A

INNER JOIN #temp1_guitarists_song AS B

ON A.guitarist_ID = B.guitarist_ID;

--display the changes

SELECT guitarist_ID,guitarist_name,song FROM #temp1_guitarists;

--clean up temp tables

DROP TABLE  #temp1_guitarists;

DROP TABLE #temp1_guitarists_song;

 

 Read More

Filtered statistics, T-SQL best practises for T-SQL Tuesday

SQL Server – I want to become a DBA. What should I first learn ?


Author: Tom Collins (http://www.sqlserver-dba.com)


Share:

Verify your Comment

Previewing your Comment

This is only a preview. Your comment has not yet been posted.

Working...
Your comment could not be posted. Error type:
Your comment has been posted. Post another comment

The letters and numbers you entered did not match the image. Please try again.

As a final step before posting your comment, enter the letters and numbers you see in the image below. This prevents automated programs from posting comments.

Having trouble reading this image? View an alternate.

Working...

Post a comment on T-SQL UPDATE JOIN on a table.


sqlserver-dba.com | SQL Server Performance Tuning | SQL Server DBA:Everything | FAQ | Contact|Copyright & Disclaimer