如何使用Powershell从数据库读取数据并根据结果进行更新?

时间:2019-06-15 00:08:10

标签: sql-server powershell

我的目标是在switch语句中使用并基于特定列中的值来读取表,这会在基于表中另一列的特定批处理文件上运行while循环。然后保存例如

ID   Name      Run    Script    Frequency  Date 
1    My Name   0      15        4          2019 05 06

读取时,如果run = 0,则上面的行应四次分配批处理文件。然后将列run更新为1。

当前,我连接到数据库,但我的switch语句未执行。我还没有看到表格的更新。

$global:Server = "server"
$global:database = "db"
$global:u = "un"
$global:p = "pw"
try {
    $ConnectionString = "server=$Server;Integrated Security=true;database=$Database;user id=$u;password=$p"
    $Connection = New-Object System.Data.SqlClient.SqlConnection
    $Connection.ConnectionString = $ConnectionString
    $Connection.Open()
} catch {
    [System.Windows.Forms.MessageBox]::Show("Failed to connect SQL Server:")
}

$Command = $Connection.CreateCommand()
$Command.CommandText ="SELECT * FROM [dbo].table WHERE Run = 0"
$table = $Command.ExecuteReader()

while ($table.Read()) {
    switch ($table.Script) {
        15 {
            $traverse = $table.Frequency
            while ($traverse -ge 0) {
                f:\oh\mybactch_file.bat $table.Date
                $traverse--
            }
            $Command.CommandText= "UPDATE dbo.table SET Run = 1 WHERE ID = $table.ID; "
            $Command.ExecuteNonQuery()
        }
    }
}
$Connection.Close()

目标是连接到数据库,然后遍历数据库并运行批处理语句。批处理完成后,更新列。

0 个答案:

没有答案