0

我创建了以下 powershell (v2) 脚本来对目标数据库执行查询并构建另一个要运行的查询/查询:

$sql = @"
DECLARE @Tables CURSOR;
DECLARE @TableName NVARCHAR(200);

BEGIN
    SET @Tables = CURSOR FOR
    SELECT TABLE_NAME
    FROM test.INFORMATION_SCHEMA.TABLES 
    WHERE TABLE_TYPE='BASE TABLE' 
    AND TABLE_NAME LIKE 'x%'

    OPEN @Tables 
    FETCH NEXT FROM @Tables 
    INTO @TableName
    WHILE @@FETCH_STATUS = 0
    BEGIN
        PRINT 'SELECT TOP 1 * FROM test.dbo.' + @TableName
        FETCH NEXT FROM @Tables 
        INTO @TableName 
    END; 

    CLOSE @Tables ;
    DEALLOCATE @Tables;
END;
"@
$ps = [PowerShell]::Create()
$ps.AddCommand("Invoke-Sqlcmd").AddParameter("Query", $sql).AddParameter("Verbose")
$ps.Invoke()

$sqlOutput = $ps.Streams.Verbose
$sqlOutputToRun = $nul
$sqlOutput | foreach {
    $sqlOutputToRun += ($_.ToString() + "`n")
}
$sqlOutputToRun = @"
$sqlOutputToRun
"@

$sqlOutputToRun

在脚本的最后,我打印了必须执行的查询,但不幸的是变量 $sqlOutputToRun 只包含大约 3/4 的预期输出。我想由于尺寸的原因,输出会以某种方式被削减,但我不确定如何扩展它。

你知道缺少什么吗?

4

2 回答 2

1

如果你不能离开你的光标,为什么你不能做这样的事情?

$sql = "
DECLARE @Tables CURSOR;
DECLARE @TableName NVARCHAR(200);
DECLARE @Results TABLE (ResultQuery NVARCHAR(MAX)) 

BEGIN
    SET @Tables = CURSOR FOR
    SELECT TABLE_NAME
    FROM testdb.INFORMATION_SCHEMA.TABLES 
    WHERE TABLE_TYPE='BASE TABLE' 
    --AND TABLE_NAME LIKE 'x%'

    OPEN @Tables 
    FETCH NEXT FROM @Tables 
    INTO @TableName
    WHILE @@FETCH_STATUS = 0
    BEGIN
        INSERT INTO @Results (ResultQuery)
        SELECT 'SELECT TOP 1 * FROM test.dbo.' + @TableName

        -- PRINT 'SELECT TOP 1 * FROM test.dbo.' + @TableName
        FETCH NEXT FROM @Tables 
        INTO @TableName 
    END; 

    CLOSE @Tables ;
    DEALLOCATE @Tables;
END;
SELECT * FROM @Results;"
$sqlOutputToRun = Invoke-Sqlcmd -query $sql
$sqlOutputToRun
于 2019-01-28T15:57:02.783 回答
1

一旦你转储print语句以支持结果集,你也可以转储游标,只需运行一个简单的查询,如:

    select 'SELECT TOP (1) * FROM '+ quotename(table_catalog) + '.' + quotename(table_schema) + '.' + quotename(table_name)
    FROM INFORMATION_SCHEMA.TABLES 
    WHERE TABLE_TYPE='BASE TABLE' 
    AND TABLE_NAME LIKE 'x%'

所以在 Powershell 中:

$sql = @"
        select 'SELECT TOP (1) * FROM '+ quotename(table_catalog) + '.' + quotename(table_schema) + '.' + quotename(table_name)
        FROM INFORMATION_SCHEMA.TABLES 
        WHERE TABLE_TYPE='BASE TABLE' 
       -- AND TABLE_NAME LIKE 'x%'
"@

$sqlOutputToRun = $nul

invoke-sqlcmd $sql | foreach { 
     $sqlOutputToRun += $_[0] + "`n"
}

$sqlOutputToRun
于 2019-01-28T16:05:37.710 回答