从具有特定命名约定的多个表插入

时间:2013-09-13 23:18:22

标签: sql sql-server

我正在尝试简化我运行以更新一个表的过程。我希望能够从以“_ASO”结尾的所有表和在特定日期之后创建的表中插入一个表。目前,我有以下代码,这些代码非常手动且经常出现很多人为错误:

INSERT INTO [DSQL].[dbo].[I3_main_AS0]
SELECT * FROM [DSQL].[dbo].[I3_table3645_AS0]

INSERT INTO [DSQL].[dbo].[I3_main_AS0]
SELECT * FROM [DSQL].[dbo].[I3_table3587_AS0]

INSERT INTO [DSQL].[dbo].[I3_main_AS0]
SELECT * FROM [DSQL].[dbo].[I3_table5421_AS0]

INSERT INTO [DSQL].[dbo].[I3_main_AS0]
SELECT * FROM [DSQL].[dbo].[I3_table69857_AS0]

是否有办法完成相同的程序1)所有以“_AS0”结尾的表和2)在某个日期之后创建的“_AS0”表?

1 个答案:

答案 0 :(得分:0)

这可以用来处理其他数据库和模式,但应该给出一般的想法。它可能使用SQL 2008中的功能。

Use DSQL

declare 
    @table sysname,
    @sql nvarchar(max),
    @startdate datetime = dateadd(Day, -14, getdate())

declare table_cursor cursor local fast_forward for
select
    name
from
    sys.tables
where
    is_ms_shipped = 0 and
    right(name, 4) = '_AS0' and
    name != 'I3_main_AS0' and -- assume we don't want to insert this into itself
    create_date >= @startDate and
    schema_id = schema_id('dbo') --simplifies things

open table_cursor

fetch next from table_cursor into @table

while @@fetch_status = 0
begin
    Set @sql = N'insert into [DSQL].[dbo].[I3_main_AS0] Select * From [DSQL].[dbo].' + quotename(@table)
    Exec sp_executesql @sql
    fetch next from table_cursor into @table
end
close table_cursor
deallocate table_cursor