批量选择FROM Information_schema.Tables

时间:2017-04-17 08:09:21

标签: sql sql-server

我想将一堆表中的记录复制到一个表中。我动态地遍历表。这适用于第一个遇到的表。但是,当它到达下一个变量表时,它会报告目标表已存在:

DECLARE @SQL nvarchar(max) = ''

SELECT @SQL = @SQL + 'select Datum, Tijd, Scanner into my_destination_table from '+ TABLE_NAME +' where tijd > 12 '
FROM Information_schema.Tables
WHERE TABLE_NAME LIKE 'tbl_%_Tijden'
EXEC sp_executesql @SQL;


Msg 2714, Level 16, State 6, Line 1
There is already an object named 'my_destination_table' in the database.

我只需要继续使用找到的记录填充my_destination_table。

有什么建议吗?

THX, 詹姆斯

@Giorgos,您的解决方案似乎正常运行。我把它调了一下,它确实有效。我不明白为什么结果加倍?这是SQL:

DECLARE @SQL nvarchar(max) = ''
declare @t nvarchar(max) = '';

select @t = min(TABLE_NAME) from Information_schema.Tables 
where TABLE_NAME > @t and TABLE_NAME like 'tbl_%_Tijden';
delete from tblfouttijden;
while @t is not null
begin
    set @SQL = 'insert into tblfouttijden (Projectnr, Datum, Start, Einde, Tijd, TijdTijd, Scanner, StartID, EindID, Naam) select Projectnr, Datum, Start, Einde, Tijd, TijdTijd, Scanner, StartID, EindID, Naam from '+ @t +' where tijd > 12 ';
EXEC sp_executesql @SQL;
-- Move to the next table, if one exists:
select @t = min(TABLE_NAME) from Information_schema.Tables WHERE TABLE_NAME > @t and TABLE_NAME LIKE 'tbl_%_Tijden';
   end

2 个答案:

答案 0 :(得分:0)

解决方案很简单。

  1. 在开始您目前正在做的事情之前,请使用CREATE TABLE my_destination_table (…)明确创建目标表。

  2. 然后,您定期SELECT … INTO my_destination_table代替INSERT INTO my_destination_table …

答案 1 :(得分:0)

这样可以避免重复:

create table tblfouttijden (Datum varchar(10), Tijd int, Scanner varchar(20)
           , ... ) ;

DECLARE @SQL nvarchar(max) = '';
declare @t nvarchar(max) = '';

select @t = min(TABLE_NAME) from Information_schema.Tables WHERE TABLE_NAME > @t and TABLE_NAME LIKE 'tbl_%_Tijden';

set @SQL = 'select Projectnr, Datum, Start, Einde, Tijd, TijdTijd, Scanner, StartID, EindID, Naam from '
          + @t +' where tijd > 12 ';

while @t is not null
begin
    select @t = min(TABLE_NAME) from Information_schema.Tables WHERE TABLE_NAME > @t and TABLE_NAME LIKE 'tbl_%_Tijden';
    if @t is not null
        set @SQL = @SQL + 'union select Projectnr, Datum, Start, Einde, Tijd, TijdTijd, Scanner, StartID, EindID, Naam from '
              + @t +' where tijd > 12 ';
end

set @SQL = 'insert into tblfouttijden (Projectnr, Datum, Start, Einde, Tijd, TijdTijd, Scanner, StartID, EindID, Naam) ' 
        + @SQL;

EXEC sp_executesql @SQL;