积极答复者
数量未知的多个表数据插入临时表

问题
答案
-
不知道是不是你要的結果,有興趣不妨參考看看。
declare @d datetime = '20120101' declare @sql nvarchar(max) = '' --建立測試資料 while @d < GETDATE() begin set @sql = N'if exists (select * from sys.objects where type = ''U'' and name = ''' + CONVERT(varchar,@d,112) + '_temp'') drop table ' + '[' + CONVERT(varchar,@d,112) + '_temp]; ' + 'create table [' + CONVERT(varchar,@d,112) + '_temp] (col1 datetime) ; ' + 'insert into [' + CONVERT(varchar,@d,112) + '_temp] values (''' + convert(varchar,@d,112) + ''')' execute sp_executesql @sql set @d = DATEADD(day,1,@d) end ----建立temp table if exists (select * from sys.objects where type = 'U' and name = 'temptable') drop table temptable create table temptable (col1 datetime) set @d = '20120101' while @d < GETDATE() begin --檢查系統資料表是否存在要寫入temp table的資料表 set @sql = N'if exists (select * from sys.objects where type = ''U''' + 'and name = ''' + CONVERT(varchar,@d,112) + '_temp'')' + 'insert into temptable ' + 'select col1 from [' + CONVERT(varchar,@d,112) + '_temp]' execute sp_executesql @sql set @d = DATEADD(day,1,@d) end select * from temptable
以上說明若有錯誤請指教,謝謝。
http://www.dotblogs.com.tw/terrychuang/- 已标记为答案 Vincent-Z 2012年3月1日 6:48
全部回复
-
不知道是不是你要的結果,有興趣不妨參考看看。
declare @d datetime = '20120101' declare @sql nvarchar(max) = '' --建立測試資料 while @d < GETDATE() begin set @sql = N'if exists (select * from sys.objects where type = ''U'' and name = ''' + CONVERT(varchar,@d,112) + '_temp'') drop table ' + '[' + CONVERT(varchar,@d,112) + '_temp]; ' + 'create table [' + CONVERT(varchar,@d,112) + '_temp] (col1 datetime) ; ' + 'insert into [' + CONVERT(varchar,@d,112) + '_temp] values (''' + convert(varchar,@d,112) + ''')' execute sp_executesql @sql set @d = DATEADD(day,1,@d) end ----建立temp table if exists (select * from sys.objects where type = 'U' and name = 'temptable') drop table temptable create table temptable (col1 datetime) set @d = '20120101' while @d < GETDATE() begin --檢查系統資料表是否存在要寫入temp table的資料表 set @sql = N'if exists (select * from sys.objects where type = ''U''' + 'and name = ''' + CONVERT(varchar,@d,112) + '_temp'')' + 'insert into temptable ' + 'select col1 from [' + CONVERT(varchar,@d,112) + '_temp]' execute sp_executesql @sql set @d = DATEADD(day,1,@d) end select * from temptable
以上說明若有錯誤請指教,謝謝。
http://www.dotblogs.com.tw/terrychuang/- 已标记为答案 Vincent-Z 2012年3月1日 6:48