问题
Hi everyone i am new to powershell. im looking for a script that will print out the affected rows from an UPDATE,INSERT,DELETE tsql using smo assembly.
i tried searching on the net and find some solution which is written from C#.. http://social.msdn.microsoft.com/Forums/sqlserver/en-US/eb9071c9-c8c2-47db-b660-2ad044af0ede/how-do-i-get-the-output-from-databaseexecutenonquery?forum=sqlsmoanddmo i dont know how to convert it to powershell.
below is a powershell script that execute tsql update using smo.
$null = [reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.ConnectionInfo")
$null = [reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoEnum ")
$null = [reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo")
$Server = new-object Microsoft.SqlServer.Management.Smo.Server
$db = $server.Databases["TESTDB"]
$result = $db.ExecuteNonQuery("UPDATE Persons set City = 'Cavite' where FirstName = 'Miguel'")
hope anyone can help. thanks.
回答1:
Try changing from ExecuteNonQuery() to ExecuteWithResults() and adding the select @@rowcount command.
$result = $db.ExecuteWithResults("UPDATE Persons Set City = 'Cavite' where FirstName = 'Miguel'; Select @@ROWCOUNT;")
$result.Tables[0].Rows[0] # to output the value of @@rowcount
来源:https://stackoverflow.com/questions/21299945/how-to-print-output-of-affected-rows-with-powershell-sqlserver-smo-assembly