Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/78.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用PowerShell检查SQL Server中是否存在行_Sql_Sql Server_Powershell - Fatal编程技术网

使用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'")

实际上,我是第一次使用PowerShell脚本编写

通过寻找一个好的解决方案,以便在SQL Server上执行
选择
,我发现以下代码:

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
,但不在循环中设置条件(当然,如果可能的话)。