Using SQL Server 2008, how to join two tables with same column names, but different datatypes

StackOverflow https://stackoverflow.com/questions/17840229

  •  04-06-2022
  •  | 
  •  

Question

I have two tables, one is a table named tree2009 and another tree2012.

Tree2009 has a total of 3657 rows, and has the columns:

  classid(bigint, not null)
  dbh(decimal(3,0),null)
  zone(nvarchar(3), null)
  inspect(nvarchar(10),null). 

Tree2012 is an updated table, 3839 rows, and has columns:

  classid(bigint, not null) 
  dbh (decimal(15,6), null)
  zone(nvarchar(254), null)
  inspect(datetime,null). 

The format of tree2012 is the preferred one, so I would like to convert the datatypes and structure of dbh, zone, inspect to the 2009 format, then COMBINE the tables based on the common column: classid.

Is this possible given the difference in rows? Sorry if I did not explain anything properly as I am new to this.

Était-ce utile?

La solution

When you say combine, I assume you want a UNION, you could create a new table with both sets:

SELECT classid
     , dbh
     , zone
     , inspect
INTO Trees
FROM Tree2012
UNION 
SELECT classid
     , CAST(dbh AS DECIMAL(15,6))
     , CAST(zone AS NVARCHAR(254))
     , CAST(inspect AS DATETIME)
FROM Tree2009

That UNION should be ALL if you want to just combine both sets (disregarding duplicates) just can't post it that way due to firewall issue, UNION will check for and remove duplicate lines between the two sets and is therefore slower.

You could also use INSERT if you just wanted to keep Tree2012:

INSERT INTO Tree2012
    SELECT classid
         , CAST(dbh AS DECIMAL(15,6))
         , CAST(zone AS NVARCHAR(254))
         , CAST(inspect AS DATETIME)
    FROM Tree2009

You don't need to CAST() every data type, ie zone in your example going from shorter nvarchar to longer nvarchar.

If you have overlapping classID's and the values for the same classID are different in each table then you might be wanting to JOIN and have multiple columns for each year:

SELECT COALESCE(a.Classid,b.Classid)'ClassID'
      , a.dbh 'dbh-2012'
      , a.zone 'zone-2012'
      , a.inspect 'inspect-2012'
      , b.dbh 'dbh-2009'
      , b.zone 'zone-2009'
      , b.inspect 'inspect-2009'
INTO NewTable
FROM Tree2012 a
FULL JOIN Tree2009 b
   ON a.Classid = b.Classid
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top