0

我用于执行 DMV 查询的辅助函数:

Function DMV_Query($DMV_Query) {
## Prepare the connection string based on information provided
$connectionString = "Provider=msolap;Data Source=$AS_Server;Initial Catalog=$CUBE;"

## Connect to the data source and open
$connection = New-Object System.Data.OleDb.OleDbConnection $connectionString
$command = New-Object System.Data.OleDb.OleDbCommand
$command.Connection = $connection 
$command.CommandText = $DMV_Query 
$connection.Open()

## Fetch the results, and close the connection
$adapter = New-Object System.Data.OleDb.OleDbDataAdapter #$command
$adapter.SelectCommand = $command 
$dataset = New-Object System.Data.DataSet
[void] $adapter.Fill($dataSet)
$connection.Close()

## Return all of the rows from their query
$dataSet.Tables[0]
}

示例调用:

$dmvResult = DMV_Query 'SELECT [SESSION_ID], [SESSION_SPID]
                        FROM $SYSTEM.DISCOVER_SESSIONS'
$dmvResult

存储在的内容示例$dmvResult

PS> $dmvResult | ConvertTo-Csv
"SESSION_ID","SESSION_SPID"     
"D0kl8975r6df65","5567"
"fghu5r67f65","2234"

我想从$dmvResult变量中选择所有列并将它们插入到 SQL 表中。这是我可以从变量中选择的方式吗?

# Doesn't work.

INSERT INTO [dbo].[Table]
SELECT * FROM @dmvResult
4

3 回答 3

1

注意:作为PowerShell 中高级字符串插值的练习,下面的答案可能很有趣,但鉴于$dmvResult包含从先前查询返回的现有DataTable对象的行,使用批量复制操作更简单,效率更高,正如发现的那样由Cataster自己撰写:请参阅此帖子


看起来您正试图通过在 PowerShell 中构造一个包含先前查询结果的字符串来创建 T-SQL 语句,$dmvResult.

由于T-SQL 对 PowerShell 变量一无所知,因此您需要在语句string中显式合并所有值以传递给您INSERT INTO的语句。

这是一个示例,基于您的示例数据,使用 PowerShell 强大的可扩展字符串(字符串插值;有关背景,请参阅此答案):

# Sample query result / imported CSV.
$dmvResult =
  [pscustomobject] @{ SESSION_ID = 'D0kl8975r6df65'; SESSION_SPID = 5567 },
  [pscustomobject] @{ SESSION_ID = 'fghu5r67f65'; SESSION_SPID = 2234 }

# Construct the INSERT INTO statement from $dmvResult, using an expandable
# string ("..." with $variable and $(<command> references))
$insertStatement = @"
INSERT INTO [dbo].[Table]
  ($($dmvResult[0].psobject.properties.name -join ', '))
VALUES
  $(
    @(foreach ($obj in $dmvResult) {
      $values = foreach ($value in $obj.psobject.properties.value) {
        if ($value -is [string]) { "`"$value`"" } else { $value }
      }
      '(' + ($values -join ', ') + ')'
    }) -join ",`n  "
  )
"@

# Output the constructed statement string.
$insertStatement

请注意,属性值的字符串化可能需要更加复杂,具体取决于您的数据;上面的代码只区分字符串和非字符串:前者用封闭字符串化"...",后者原样。

以上产生:

INSERT INTO [dbo].[Table]
  (SESSION_ID, SESSION_SPID)
VALUES
  ("D0kl8975r6df65", 5567),
  ("fghu5r67f65", 2234)
于 2019-01-31T19:01:52.753 回答
0

我找到了一个解决方案,BulkCopy!

$dmvResult = DMV_Query 'SELECT [SESSION_ID]
      ,[SESSION_SPID]
FROM $SYSTEM.DISCOVER_SESSIONS';

$ConnectionString ='Data Source=$server; Database=$database; Trusted_Connection=True;'
$bulkCopy = new-object Data.SqlClient.SqlBulkCopy($ConnectionString)
$bulkCopy.DestinationTableName=$Table
$bulkCopy.WriteToServer($dmvResult)

但是,如果列不按顺序排列,则无法正确映射列,因为 BulkCopy 按位置复制,而不是按名称匹配

于 2019-01-31T21:11:48.073 回答
0

使用如下查询,不要将值存储在变量中..

INSERT INTO [dbo].[Table]
SELECT [SESSION_ID]
      ,[SESSION_SPID]`enter code here`
FROM $SYSTEM.DISCOVER_SESSIONS
于 2019-01-31T17:24:24.010 回答