Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Powershell get Values from sql table

we know that we can use sql query window to get values from Database like "select * from....". Is there any way to get a value through powershell way. I found the way to database table itself but not to the values..

Ex:

Set-location SQLserver:\sql\default\localhost\databases\database\tables
Get-childitem 

Above command gives me tables in the DB , but how can i get the values from it.

like image 279
Jegan.M Avatar asked May 30 '15 07:05

Jegan.M


People also ask

How get all values from table in SQL?

SELECT statements SELECT column1, column2 FROM table1, table2 WHERE column2='value'; In the above SQL statement: The SELECT clause specifies one or more columns to be retrieved; to specify multiple columns, use a comma and a space between column names. To retrieve all columns, use the wild card * (an asterisk).

Can I use SQL in PowerShell?

SQL PowerShell cmdlets can be used to manage instances of Azure SQL Database, Azure Synapse Analytics, and all supported SQL Server products.

Can PowerShell connect to SQL Server?

SQL Server provides a PowerShell module named SqlServer. You can use the SqlServer module to import the SQL Server components (SQL Server provider and cmdlets) into a PowerShell environment or script.


2 Answers

Most concise and straightforward option is Invoke-SqlCommand

$results = Invoke-Sqlcmd -ServerInstance "mySqlServer" -Database "myDatabase" -Query "SELECT * FROM MyTable"
like image 199
Brent Avatar answered Sep 24 '22 23:09

Brent


You can use this

$connectionString = “Server=$dataSource;uid=$user; pwd=$pwd;Database=$database;Integrated Security=False;”

$connection = New-Object System.Data.SqlClient.SqlConnection
$connection.ConnectionString = $connectionString

$connection.Open()
$query = “SELECT * FROM Tab”

$command = $connection.CreateCommand()
$command.CommandText = $query

$result = $command.ExecuteReader()
like image 23
Polux Avatar answered Sep 21 '22 23:09

Polux