SQL: Insert into statement, but suppose you do not know origin and target headers

坚强是说给别人听的谎言 提交于 2019-12-24 08:08:09

问题


I am trying to come up with an insert sql stament that will insert data from a table into another existing table. There are in fact some ways of doing this but I did not find a way that matches my requirements.

I need an insert statement type query that will insert data into another table but it does not knows which headers both table have. For instance the origin table has 25 headers and the target one has 20, which 10 of them match in name. I would like to transfer the ones that are matching the name of the headers ignoring the rest.

Hope I was clear and hope anyone will be able to help me


回答1:


I think you have to get the two tables columns then filter em to get match columns names after that you can build your insert into statement and exec it

to get columns exists in both table

Declare @cols varchar(max)

SELECT  @cols =COALESCE(@cols +',','')+'['+COLUMN_NAME+']'
FROM DbName.INFORMATION_SCHEMA.COLUMNS 
WHERE TABLE_NAME = N'security' and COLUMN_NAME in( 
      SELECT COLUMN_NAME
      FROM DbName.INFORMATION_SCHEMA.COLUMNS 
      WHERE TABLE_NAME = N'debt_securities')

then create insert statement

declare @query varchar(max)='insert into debt_securities('+@cols+')
                             select '+@cols+' from [security]'

then execute it

exec(@query)



回答2:


I can not think of a single query which can do all this, but you can definitely write a sql server procedure to do this.

you can get the list of column names and datatype of the columns for the source and destination table from the following query

SELECT COLUMN_NAME 
FROM INFORMATION_SCHEMA.COLUMNS 
WHERE TABLE_NAME = 'TABLENAME'

With this you can run a loop in the pl/sql to find out matching columns based on name and datatype and then form a on the fly dynamic plsql and execute it. this should solve your purpose i guess.



来源:https://stackoverflow.com/questions/6844137/sql-insert-into-statement-but-suppose-you-do-not-know-origin-and-target-header

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!