Is there a way to select the row from a temp table (table has only one row anyway), into another table that has some columns with differenet names? For example:
TempTable
FirstName LastName Column1 Column2
------------ ------------ ----------- -----------
Joe Smith OKC TX
OtherTable
FirstName LastName Region1 Region2 Region3
------------ ------------ ----------- ----------- ----------
NULL NULL NULL NULL NULL
I need to copy the data, in the same order as the columns from TempTable into OtherTable. TempTable will not always be the same….as in sometimes it will have 3 columns, sometimes just 2…etc. If it does not have the same number of columns as OtherTable, the the remaining “Region” columns should stay null.
The end result should be:
OtherTable
FirstName LastName Region1 Region2 Region3
------------ ------------ ----------- ----------- ----------
Joe Smith OKC TX NULL
PLUS the column names in TEMPTable will NEVER be the same…as in one time it will be “Column1″…the next time it could be “XXXXX1”. That’s why I just want to copy data only…the data will always be in the correct order…
LOL…does this even make sense? This is for SQL Server 2005
EDIT …….. Dynamic SQL Generation added
This code will generate INSERT statements to INSERT from #TEMP into #TEMP. You can tweak it to suit your purpose if you are going from #temp to regular tables.
OLD ANSWER
Yes you can do this but you have to write different statements for each type of
INSERT. You do have to specify column names in both places – theINSERT INTOand theSELECTIf you have the same number of columns in your Source and Destination tables, do this
What this will do is map as follows:
MyTable.MyColumn01 -> Table1.Column1
MyTable.MyColumn02 -> Table1.Column2
MyTable.MyColumn03 -> Table1.Column3
If the Source has less columns, you can use a NULL value in place of the column name
OR you can just use two column names
If the destination table has less columns than the source, then you have to ignore columns from the source