SQL查询作为Powershell中的事务

时间:2019-02-27 06:02:16

标签: sql powershell

我希望在PowerShell中作为事务执行一些SQL查询。但是,我遇到错误,找不到合适的答案。 除了错误之外,BeginTransaction()和CommitTransaction()是在Powershell中执行事务的方式吗? Intellisense似乎没有显示CommitTransaction()方法。

错误:

Exception calling "ExecuteNonQuery" with "0" argument(s): "ExecuteNonQuery requires the command to have a transaction when the connection assigned to the command is in a pending local transaction.  The Transaction property of the command has not been 
initialized

代码:

try {
    #SQL Connection
    $Connection = New-Object System.Data.SQLClient.SQLConnection
    $Connection.ConnectionString = "Server=$server,1433;Initial Catalog=$Database;Persist Security Info=False;User ID=$UserID;Password=$Password;MultipleActiveResultSets=true;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;;"

    $Connection.Open()

    $Command = New-Object System.Data.SQLClient.SQLCommand
    $Command.Connection = $Connection

    #Begin Transaction
    $Connection.BeginTransaction()

    #INSERT into PROJECT table 
    $input_2 = $projectName
    $input_3 = $blobUri + $configFileName
    $input_4 = $key
    $input_5 = $projectType
    $input_6 = $projectIsActive

    $sql =
    "
    begin 
        INSERT INTO PROJECT 
        ([PROJECT_NAME],[CONFIGURATION_LOCATION],[ENCRYPTION_KEY],[PROJECT_TYPE],[IS_ACTIVE],[CREATED_DATETIME])
        select '$input_2', '$input_3', '$input_4', '$input_5', '$input_6', cast(CONVERT(datetimeoffset,GETDATE()) AT TIME ZONE 'AUS Eastern Standard Time' as datetime)
    end
    " 
    $Command.CommandText = $sql
    $Command.ExecuteNonQuery()

    #Get Project ID from PROJECT table
    $sql =
    "
    begin 
        SELECT TOP 1 PROJECT_ID FROM PROJECT WHERE PROJECT_NAME='$projectName'
    end
    " 
    $Command.CommandText = $sql
    $projectID = $Command.ExecuteScalar() 


    #Commit Transaction
    $Connection.CommitTrasaction()

    #Close Connection
    $Connection.Close()
}
Catch {
    throw   

}

1 个答案:

答案 0 :(得分:2)

您必须将Transaction的{​​{1}}属性设置为SqlCommand返回的交易对象:

BeginTransaction