循环访问表中的字段



我想获取数据库中表的名称,并在另一个数据库中创建一个包含数据的表。

表名称每周都不同,所以我试图做一些自动化。

Iv 创建了一个带有表名称的临时表。我不确定如何遍历表并为每个表名运行 SQL 语句。

除了创建临时表之外,我没有任何代码。

创建临时表。接下来呢?

一种可能的方法(没有临时表(是生成并执行动态语句:

USE [CurrentDatabase]
DECLARE @stm nvarchar(max) = N''
SELECT @stm = STUFF(
    (
        SELECT CONCAT(
            N'; SELECT * ',
            'INTO [NewDatabase].',
            QUOTENAME(sch.[name]),
            N'.',
            QUOTENAME(tab.[name]),
            N' FROM ',
            QUOTENAME(sch.[name]),
            N'.',
            QUOTENAME(tab.[name]),
            N'WHERE 1 = 0 '
        )
        FROM sys.tables tab 
        JOIN sys.schemas sch ON tab.schema_id = sch.schema_id
        WHERE tab.[type] = 'U'
        FOR XML PATH('')
    ), 1, 1, N''
)
PRINT @stm
EXEC sp_executesql @stm

您可以使用以下命令获取表名称并将其插入临时表中:

TRUNCATE TABLE YOUR_TEMP_TABLE
INSERT INTO YOUR_TEMP_TABLE THE_COLUMN_NAME 
SELECT table_name FROM information_schema.tables 
WHERE TABLE_TYPE='BASE TABLE' 
我包括截断表

是因为正如您所说,表名经常更改,它是一个临时表,因此截断每次都会为您提供"干净的石板"。

我认为这就是你所追求的。

    --assuming both dbs are with-in the same server
    --select top 10 name into TempTableList from SourceDBName..sysobjects  where xtype='u' and uid=1
    declare @sourceDB varchar(100),
            @Table varchar(100)
    set @sourceDB='SourceDBName.SchemaName.'        
    -- if you are working with different schema have them listed in your temp table
    declare generateTable cursor 
    for
    select * from TempTableList -- The temp table that you already have data with
    Open generateTable
    fetch next from generateTable into @Table
    while @@FETCH_STATUS =0
    begin
    /*Same drill if you need them to be on specific schemas, you can alter this part.*/
    exec('select top 0 * into '+@Table+'_new from ' +@sourceDB+ @Table)
    fetch next from generateTable into @Table
    end
    close generateTable
    deallocate generateTable

如果您想用相同的数据填充它们,那么只需这样做

    exec('select * into '+@Table+'_new from ' + @Table)

最新更新