how to print output of affected rows with powershell sqlserver smo assembly

若如初见. 提交于 2021-02-11 15:55:48

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!