0

我正在尝试简化为更新一个表而运行的过程。我希望能够从以“_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]

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

4

1 回答 1

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
于 2013-09-13T23:37:01.500 回答