Updating tables without naming all columns

Samter picture Samter · Aug 27, 2012 · Viewed 10.1k times · Source

I have found a way to make two tables from different databases match each other using this template:

INSERT [DestDB].[dbo].[TABLE]
SELECT source.* FROM 
[SourceDB].[dbo].[TABLE] AS source
LEFT OUTER JOIN
[DestDB].[dbo].[TABLE] AS dest
ON 
source.[PKColumn] = dest.[PKColumn]
WHERE dest.[PKcolumn] IS NULL

UPDATE dest
SET 
 dest.[PK_COLUMN1] = source.[PK_COLUMN1]
,dest.[COLUMN2] = source.[COLUMN2]
,dest.[COLUMN3] = source.[COLUMN3]
,dest.[COLUMN4] = source.[COLUMN4]
,dest.[COLUMN5] = source.[COLUMN5]
,dest.[COLUMN6] = source.[COLUMN6]
,dest.[COLUMN7] = source.[COLUMN7]
,dest.[COLUMN8] = source.[COLUMN8]

FROM 
[SourceDB].[dbo].[TABLE] AS source
INNER JOIN 
[DestDB].[dbo].[TABLE] AS dest
ON source.[PK_Column1] = dest.[PK_Column1]

However some tables I am working with have at least 200 columns and while it is possible to do this through the power of Copy + Paste, I just need to know if there is a way that doesn't involve me getting Carpel Tunnel Syndrome.

I am using Microsoft SQL Server 2005.

Any advice?

Answer

Chris Gessler picture Chris Gessler · Aug 27, 2012

I don't think you can update columns without naming them, but you can use SQL and the sys.columns view to script it for you:

select ',dest.[' + name + '] = source.[' + name +']' 
from sys.columns 
WHERE object_id = OBJECT_ID(N'[dbo].[Widgets]')

-- output --

,dest.[WidgetId] = source.[WidgetId]
,dest.[WidgetName] = source.[WidgetName]
,dest.[CreatedDt] = source.[CreatedDt]
,dest.[WidgetValue] = source.[WidgetValue]
,dest.[ModifiedDt] = source.[ModifiedDt]

The only other way is to NOT update, but instead truncate the dest table and perform a SELECT INTO

SELECT * INTO DEST FROM SOURCE