Sql server 如何合并许多类似的表?

Sql server 如何合并许多类似的表?,sql-server,ssms-2012,Sql Server,Ssms 2012,我有很多表,它们都有相同的结构和相似的表名,我正在寻找一种方法,将其中的一些列合并到一个新表中,其中包含两个额外的列:一个自动生成的整数PK和源表的名称。e、 g UniqueID SourceID、Xcoord、Ycoord、Zcoord、SourceTable 我设法创建了一个表,其中包含我想要使用的所有表的列表,但不知道下一步该怎么做 SELECT [name] INTO PointTables FROM [Surveys].[sys].[tables] where [name] like

我有很多表,它们都有相同的结构和相似的表名,我正在寻找一种方法,将其中的一些列合并到一个新表中,其中包含两个额外的列:一个自动生成的整数PK和源表的名称。e、 g

UniqueID SourceID、Xcoord、Ycoord、Zcoord、SourceTable

我设法创建了一个表,其中包含我想要使用的所有表的列表,但不知道下一步该怎么做

SELECT [name]
INTO PointTables
FROM [Surveys].[sys].[tables]
where [name] like '%CoordDB'

对这个问题不是很清楚。 这些表的列名称是否相同? 是否要插入到点表中

您可以创建以下表格:

create table PointTables(
UniqueID    int identity
, Xcoord    int
, Ycoord    int
, Zcoord    int
, SourceTable   varchar(50)
之后,您可以在sp_executesql命令和连接的帮助下插入表

declare @command nvarchar(max) 
select @command = 'insert into PointTables(Xcoord,YCoord,ZCoord,SourceTable)
select [Xcoord],[YCoord],[Zcoord],'''+name+''' from '+name from sys.tables where name like '%CoordDB%'
execute sp_executesql @command

查理·卢克曼的回答是一个很好的开始,但出于某种原因,只在第一张桌子上起作用。我查看了其他几篇文章,发现了游标,它允许您使用WHILE循环构建/连接多个INSERT-in命令,一次只处理一行。虽然这在我对5个表的测试中有效,但当我得到100或1000个表时,我担心性能

declare @command nvarchar(max) 
declare @tblname varchar(50)
declare TableCursor Cursor
    FOR SELECT name FROM sys.tables where name like '%%DB_COORD'
SET @command = ''
OPEN TableCursor
    FETCH NEXT FROM TableCursor INTO @tblname

    WHILE @@FETCH_STATUS <> -1
    BEGIN
        select @command =  @command + 'INSERT into MasterPoints(SourceID, Xcoord, Ycoord, Zcoord, PtCode, SourceTable)  SELECT UPTNUM, EAST, NORTH, ELEVATION, CODE,''' + @tblname + '''from "' + @tblname + '" '
        FETCH NEXT FROM TableCursor INTO @tblname
    END
CLOSE TableCursor
DEALLOCATE TableCursor

execute sp_executesql @command
declare@command-nvarchar(最大值)
声明@tblname varchar(50)
声明表游标游标
对于从sys.tables中选择名称,其中的名称类似于“%%DB_COORD”
设置@command=''
打开表格光标
从TableCursor获取下一个到@tblname
而@@FETCH\u状态为-1
开始
选择@command=@command+'插入到主控点(SourceID、Xcoord、Ycoord、Zcoord、PtCode、SourceTable)从“++@tblname+”中选择upnum、东、北、高程、代码“++@tblname+””
从TableCursor获取下一个到@tblname
结束
关闭表格光标
取消分配表游标
执行sp_executesql@命令
选择distinct[源表]
从[Manifold].[dbo].[MasterPoints]

您可以使用sys.tables获取表名,但是如何将列与sys.column联接显示您有多少个表?当我遇到类似情况时,我使用联合操作,然后将该查询插入到一个新表中。在我的例子中,两个新列是一个标识列和一个计算列。谢谢-这让我接近了,但只从它找到的第一个表中获取数据。在四处搜索后,我发现提到了游标,但还不知道如何使用它们。事实上,你可以通过循环来解决一些问题。创建一个包含两列的表:id和tablename。Id列是自动递增的,用于循环。循环比游标具有更好的性能和更简单的语法。谢谢。当我开始处理真实数据时,性能将成为一个问题,因此我将在下一轮中尝试。