使用PowerShell检查SQL Server中是否存在行
实际上,我是第一次使用PowerShell脚本编写 通过寻找一个好的解决方案,以便在SQL Server上执行使用PowerShell检查SQL Server中是否存在行,sql,sql-server,powershell,Sql,Sql Server,Powershell,实际上,我是第一次使用PowerShell脚本编写 通过寻找一个好的解决方案,以便在SQL Server上执行选择,我发现以下代码: Function IdentityProviderExistsDatabase { param( [string] $IdPIdentifier ) $SQLQuery = $("SELECT [*] FROM [dbo].[IdPs] WHERE [IdPIdentifier] = '$IdPIdentifier'")
选择
,我发现以下代码:
Function IdentityProviderExistsDatabase {
param(
[string] $IdPIdentifier
)
$SQLQuery = $("SELECT [*] FROM [dbo].[IdPs] WHERE [IdPIdentifier] = '$IdPIdentifier'")
$SQLConnect = new-object system.data.sqlclient.sqlconnection
$SQLConnect.connectionstring = $SQLConnectionString
$SQLConnect.Open()
$command = New-object system.data.sqlclient.SqlCommand
$command.connection = $SQLConnect
$command.CommandText = $SQLQuery
$Reader = $command.ExecuteReader()
while ($Reader.Read()) {
$Reader.GetValue($1)
}
}
上面的解决方案很好,但实际上我不需要读取任何值;出于我的目的,根据WHERE
子句,我只知道查询是否返回了一些内容,因此只知道记录是否存在
有没有比检查循环中的返回值更优雅的方法来执行此操作?您可以像检查计数一样
$SQLQuery = $("SELECT count(*) result_count FROM [dbo].[IdPs] WHERE [IdPIdentifier] = '$IdPIdentifier'")
它将返回一行使用ExecuteScalar()
。根据文件
使用ExecuteScalar方法检索单个值(例如,
来自数据库的聚合值
示例用法:
$SQLQuery = "SELECT count(*) FROM..."
$SQLConnect = new-object system.data.sqlclient.sqlconnection(...)
$SQLConnect.Open()
$command = New-object system.data.sqlclient.SqlCommand
$command.connection = $SQLConnect
$command.CommandText = $SQLQuery
$scalar = $command.ExecuteScalar() # The select's result is stored in $scalar
$command.Dispose()
$SQLConnect.Dispose()
最简单的SQL应该是:
SQLQuery=$([dbo].[IdPs]中选择前11行存在,其中[IdPIdentifier]='$IdPIdentifier')
I秒top11
方法超过计数,这是值得的。首先,谢谢。我的问题不是关于查询,而是关于如何正确使用读卡器,以便在记录存在与否的情况下获得$true
或$false
,但不在循环中设置条件(当然,如果可能的话)。