我有一个脚本,运行一条select语句,然后通过一个阅读器,但是当该语句中没有返回任何行时,它将跳过阅读器,并稍后在脚本中导致错误。
我希望脚本可以执行以下任一操作:
(a)如果select语句返回行,请遍历阅读器并完成脚本,或者
(b)如果未返回任何行,请执行其他操作,并向主机写入未返回任何行的信息。
这是我目前在脚本的那部分内容:
$SQLQuery = $("SELECT [Column1] FROM [MyDatabase].[dbo].[MyTable] WHERE Column1 > 0")
$Connection = New-Object System.Data.SQLClient.SQLConnection
$Connection.ConnectionString = "server='$Server';database='$Database';trusted_connection=true;"
$Connection.Open()
$Command = New-Object System.Data.SQLClient.SQLCommand
$Command.Connection = $Connection
$Command.CommandText = $SQLQuery
$Reader = $Command.ExecuteReader()
while ($Reader.Read()) {
## do some stuff
}
$Connection.Close()
## The rest of the script.....
我想让我的脚本这样做:
IF (SQL output returns rows) {
do stuff
}
ELSEIF (SQL output returns 0 rows) {
tell me 0 rows were returned
}
谢谢。
最佳答案
检查SqlDataReader上的HasRows属性
您可能要先执行if检查,看看是否有返回的行,然后查看是否有返回的行,然后继续读取它们。
If ($Reader.HasRows) {
//read your rows.
}
else
{
no rows returned...
}
关于sql - PowerShell:如何确定SQL查询是否返回0行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37122590/