使用Powershell中的select SQL语句检索数据

前端之家收集整理的这篇文章主要介绍了使用Powershell中的select SQL语句检索数据前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我的目标是分配返回给变量的结果的值:
$sqlConnection = New-Object System.Data.sqlClient.sqlConnection
$sqlConnection.ConnectionString = "Server=HOME\sqlEXPRESS;Database=master;Integrated Security=True"
$sqlCmd = New-Object System.Data.sqlClient.sqlCommand
$sqlCmd.CommandText = "select name from sysdatabases where name = 'tempdb'"
$sqlCmd.Connection = $sqlConnection
$sqlAdapter = New-Object System.Data.sqlClient.sqlDataAdapter
$sqlAdapter.SelectCommand = $sqlCmd
$DataSet = New-Object System.Data.DataSet
$sqlAdapter.Fill($DataSet)
$sqlConnection.Close()
$DataSet.Tables[0]

返回的值显然应该是’tempdb’,那么如何将它分配给一个变量呢?

Write-output "Database is " $variablename

所需输出数据库是tempdb

解决方法

$sqlConnection = New-Object System.Data.sqlClient.sqlConnection
$sqlConnection.ConnectionString = "Server=HOME\sqlEXPRESS;Database=master;Integrated Security=True"
$sqlConnection.Open()
$sqlCmd = New-Object System.Data.sqlClient.sqlCommand
$sqlCmd.CommandText = "select name from sysdatabases where name = 'tempdb'"
$sqlCmd.Connection = $sqlConnection
$dbname = $sqlCmd.ExecuteScalar()
$sqlConnection.Close()
Write-output "Database is " $dbname

猜你在找的MsSQL相关文章