如何更新数据表并提交回sql server源

问题描述

好的,所以我有一个包含一些数据的表格。下面是 SQL server 中 table def 的截图:

table def in sql

还有一个应用程序可以填充表中的一些数据。这是示例数据的屏幕截图。除 [emailSentCount] 之外的所有列均由外部应用填充。

Sample data

现在我的问题是使用我正在尝试构建的 Powershell 脚本来使用这些数据并发送电子邮件通知。我在 DataTable 中读取了表格的所有内容。我浏览每一行并决定是否必须为该行发送电子邮件。如果是这样,那么我发送电子邮件并通过向其中添加 + 1 来更新 [emailSentCount] 列。

在脚本的末尾,我尝试将我对 DataTable 所做的这些更改发送回 SQL 服务器上的表。但是我收到一个错误:

PS error

这是我正在使用的脚本。

param(
    [string]$SQLServerName="SQLServerName\InstanceName",[string]$SQLDatabaseName="DBName",[string]$SQLTableName = "UserList",[string]$SQLSelectQuery="SELECT * FROM $SQLTableName"    
)

cls


Function SendEmail
{
    Param(
        [string]$ToMailAddress,[int]$MessageTemplate
        
    )

    [string]$MessageBody=$null

    switch ($MessageTemplate)
    {
        1 {$MessageBody = Test new certificate issued. Please ignore!}
        2 {$MessageBody = Test existing certificate renewed. Please ignore!}
    }


    $from = "[email protected]"
    $to = $ToMailAddress
    $smtp = "smtp.example.net" 
    Send-MailMessage 
        -From $from 
        -To $to 
        -Subject $MessageBody 
        -SmtpServer $smtp 

}


$sqlConn = New-Object System.Data.SqlClient.SqlConnection
$sqlConn.ConnectionString = “Server=$SQLServerName;Integrated Security=true;Initial Catalog=$SQLDatabaseName”
$sqlConn.Open()

$sqlCommand = $sqlConn.CreateCommand()
$sqlCommand.CommandText = $SQLSelectQuery


$dataAdapter = New-Object System.Data.SqlClient.SqlDataAdapter $sqlCommand
$dataTable = New-Object System.Data.DataTable
$dataAdapter.Fill($dataTable) | Out-Null



foreach($dataRow in $dataTable.Rows)
{
    write-host $dataRow["shouldSendEmail"]
    if($dataRow["shouldSendEmail"] -eq $true)
    {
        # First send email depending on whether its a first time new cert or a cert renewal.
        if($dataRow["certRenewal"] -eq $true)
        {
            SendEmail -ToMailAddress $dataRow["email"] -MessageTemplate 2
        }
        else
        {
            SendEmail -ToMailAddress $dataRow["email"] -MessageTemplate 1
        }
        
        # After you have sent the email,increase the emailSentCount value in the datatable.
        $dataRow["emailSentCount"] = $dataRow["emailSentCount"] + 1

        #Also reset the shouldSendEmail column to $false/0
        $dataRow["shouldSendEmail"] = $false
  
    }
}

$dataAdapter.Update($dataTable)


$sqlConn.Close()

看来我需要包含一些更新命令。但是在这种情况下它会是什么样子,它需要包含在什么地方?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)