【问题标题】:Querying data from SQL Server table with Powershell使用 Powershell 从 SQL Server 表中查询数据
【发布时间】:2021-04-27 00:05:06
【问题描述】:

由于某些技术原因,我需要将 xlsx 文件记录上传到 SQL Server 表中,主要目标是进行某种增量加载:我们每天有一个新文件,我想比较数据库的带有新 xlsx 文件的表,遍历前 50'000 行(为此,我将第一个 ID 行降序排列)然后如果我们有不同的行,则在 SQL Server 表中删除并从xlsx 文件。问题是我正在尝试连接到数据库的表,但看起来没有任何结果

$datasource = "server" 
$user = "account"
$pass = "password"
$database = "databse"
$connectionString = “Server=$dataSource;uid=$user; pwd=$pwd; Database=$database; Integrated Security=True;"


$connection = New-Object System.Data.SqlClient.SqlConnection
$connection.ConnectionString = $connectionString
$connection.Open()

$query = “SELECT * FROM [XXX].[dbo].[Originaltable]”

$command = $connection.CreateCommand()
$command.CommandText = $query

$table = new-object “System.Data.DataTable”
$table.Load($result)

我做错了什么?

【问题讨论】:

  • 什么是$result?而且您似乎从未执行过$command
  • 如果您使用的是 Windows 身份验证,则不需要硬编码凭据,对吧?

标签: powershell


【解决方案1】:

在您的示例中,您缺少一个实际连接的命令:

$command.CommandText = $query
<# Add: #> $result = $command.ExecuteReader()
$table = New-Object System.Data.DataTable
$table.Load($result)

我建议您尝试使用SqlServer powershell 模块命令。它们本质上是一样的,所以这是个人喜好。

# Invoke-Sqlcmd can take a query and returns an object
$table = Invoke-Sqlcmd -ServerInstance "$Server\$InstanceName" -Database $database -Username $user -Password $pass `
    -Query 'SELECT * FROM [XXX].[dbo].[Originaltable]'

# Read and Write-SqlTableData are better when you don't need to filter anything out:
# Example using integrated security
$table = Read-SqlTableData -ServerInstance "$Server\$InstanceName" `
    -SchemaName dbo `
    -Database $database `
    -TableName Originaltable `
    -TopN 50000

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-17
    • 1970-01-01
    • 2018-04-08
    • 2012-01-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多