2015-07-11 42 views
0

我有很多表都具有相同的結構和類似的表名稱,並且正在尋找一種方法來將它們中的幾列全部合併到一個具有兩個額外列的新表中:一個自動生成的整數PK,以及源表。例如,如何合併很多類似的表格?

的UniqueID的SourceID,XCOORD,YCOORD,Zcoord,sourceTable會

我設法創建一個包含所有我想要使用的表的列表的表,但不知道下一步該怎麼做。

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

您是通過使用SYS.TABLES獲取表名,但有關柱用什麼SYS.COLUMNS加入 – mohan111

+0

多少你有桌子嗎?當我遇到類似的情況時,我使用聯合操作,然後將該查詢插入到新表中。在我的情況下,兩個新列是一個標識列和一個計算列。 – 2015-07-11 04:01:30

回答

0

不是很清楚這個問題。 這些表的列名是否相同? 你想插入到PointTables?

您可以創建表:

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 
+0

謝謝 - 這讓我關閉,但只抓住它找到的第一個表中的數據。在四處搜尋後,我發現提及了遊標,但不知道如何使用它們。 –

+0

嗯,實際上你可以用循環做一些解決方法。創建一個包含2列的表:id和tablename。 Id列是自動增量,用於循環。循環比遊標具有更好的性能和更簡單的語法。 –

+0

謝謝。當我開始處理真實數據時,性能將成爲問題,所以我會在下一輪嘗試。 –

0

從查理·盧克曼答案是一個良好的開端,但對於一些原因只在第一張桌子上工作。我查看了其他幾篇文章,並發現了一些遊標,這些遊標允許您使用WHILE循環一次構建/連接多個INSERT INTO命令,從而一次處理一行代碼。雖然這在我對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 

SELECT DISTINCT [sourceTable會] FROM [歧管] [DBO]。[MasterPoints]