简体   繁体   English

将所有数据从一个动态创建的表移动到另一个不包括某些列

[英]Moving All Data From One Dynamic Created Table To Another Excluding Some Columns

I am creating two identical tables dynamically from JSON.我正在从 JSON 动态创建两个相同的表。 Lets Call Them Test1.Table , Test2.Table .让我们称它们为Test1.Table , Test2.Table

Test.Table1 is then loaded with data in it's columns by someone else. Test.Table1然后由其他人加载其列中的数据。

My Issue is that now, I want to create a stored procedure that creates a stored procedure that takes all the data from Test.Table1 and inserts them into Test.Table2 , which would be easy, except I don't want to take all the columns from Test.Table1 , I want all but 3 of them.我的问题是,现在,我想创建一个存储过程,该过程创建一个存储过程,该过程从Test.Table1获取所有数据并将它们插入到Test.Table2 ,这很容易,除非我不想获取所有数据Test.Table1列,我想要除 3 之外的所有列。

I can't do a SELECT (col1, col2, col4, col5...etc) INTO Test.Table2 FROM Test.Table1 because the columns are dynamic every time, and the table already exists.我不能做一个SELECT (col1, col2, col4, col5...etc) INTO Test.Table2 FROM Test.Table1因为列每次都是动态的,并且表已经存在。

I can't do use a temporary table to move Test.Table1 's data into and drop the columns I don't want and insert it into Test.Table2 Because the columns wouldn't match up.我不能使用临时表将Test.Table1的数据移入并删除我不想要的列并将其插入到Test.Table2因为列不匹配。

Here is a quick script to get you started.这是一个快速脚本,可帮助您入门。 I created two tables in tempdb with slightly different table structures and wrote it such that you can insert from the first one to the second one where the columns match up.我在 tempdb 中创建了两个表,表结构略有不同,并编写了它,以便您可以从第一个插入到列匹配的第二个。 You can change the table structure and the query will change accordingly.您可以更改表结构,查询也会相应更改。 The query is based on the second table.查询基于第二个表。 This is part of the design, you may wish to swap that around.这是设计的一部分,您可能希望交换它。

Use tempdb;
Go

If OBJECT_ID ('tempdb..##Temp1') is not null Drop Table ##Temp1
If OBJECT_ID('tempdb..##Temp2') is not null Drop Table ##Temp2

Create Table ##Temp1 (col1 int, col2 int, col3 int, col4 int)
Create Table ##Temp2 (col1 int, col2 int, col4 int)

Declare @max int
Declare @sql nvarchar(max)

Select @max = max(ordinal_position)
from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME = '##Temp2' 

Select @sql = 
STRING_AGG(
case when ordinal_position = 1 then 'Insert into ##Temp2 ('+COLUMN_NAME+',' 
when ORDINAL_POSITION = @max then COLUMN_NAME +')'
else COLUMN_NAME+', ' end,'') + string_agg (
case when ordinal_position = 1 then ' Select '+COLUMN_NAME+', ' when ORDINAL_POSITION = @max 
Then COLUMN_NAME +' From ##Temp1' else COLUMN_Name + ', ' end,'')
from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME = '##Temp2'

EXEC sp_executesql @sql

Hope this helps.希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM