Read multiple tables from dataset in Powershell - sql

I am using a function that collects data from a SQL server:
function Invoke-SQLCommand {
param(
[string] $dataSource = "myserver",
[string] $dbName = "mydatabase",
[string] $sqlCommand = $(throw "Please specify a query.")
)
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = `
"Server=$dataSource;Database=$dbName;Integrated Security=True"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = $sqlCommand
$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]
}
It works great but returns only one table. I am passing several Select statements, so the dataset contains multiple tables.
I replaced
$DataSet.Tables[0]
with
for ($i=0;$i -lt $DataSet.tables.count;$i++){
$Dataset.Tables[$i]
}
but the console only shows the content of the first table and blank lines for each records of what should be the second table. The only way to see the result is to change the code to
$Dataset.Tables[$i] | out-string
but I do not want strings, I want to have table objects to work with.
When I assign what is returned by the Invoke-SQLCommand to a variable, I can see that I have an array of datarow objects but only from the first table. What happened to the second table?
Any help would be greatly appreciated.
Thanks

I tried your function (that returns $DataSet.Tables) and it worked pretty well for me. This command returned rows from both tables:
$t = Invoke-sqlcommand '.\sql2005' 'AdventureWorksDW' `
"SELECT * FROM DimOrganization; SELECT * FROM DimSalesReason"
$t[0] #returns rows from first table
$t[1] #returns rows from second table
Anyway, what I would recommend:
First I would discard output from Fill:
$SqlAdapter.Fill($DataSet) > $null
It is returned as well, but that's not probably desired.
As in your case Invoke-SqlCommand doesn't work, I would try to return 1 dim array like this:
function Invoke-SQLCommand {
...
,$DataSet.Tables
}
Consider that PowerShell treats DataTable specially and when trying to format it, it unravels Rows collection (credits to x0n). That's why just executing $t from my example displays all the rows returned from the command.

Thank you for your answer.
Well, I can't explain why it works for you and not for me.
If I run the exact same command as you (except for the data source, mysqlserver\sqlexpress in my case), $t[0] only returns the first row of the first table and $t[1] the second row.
What seems to be happening in my case is that the rows from all tables are merged so I end up with one big set of datarows, not the individual tables expected.
I ended replacing:
for ($i=0;$i -lt $DataSet.tables.count;$i++){
$Dataset.Tables[$i]
}
with just
$Dataset
I can then reference the individual tables from my script by using $t.Tables[0] and $t.Tables[1].
Thanks again

Related

How to scroll a resultset from an ODBC datasource using cursors in PowerShell?

How do I use a cursor to scroll a resultset from an ODBC datasource in PowerShell ?
Problem:
The SQL statement takes too long to execute (due to returning millions of rows). I only want to return the top 5 rows but this database does not support the top, limit or rownum select statement clauses).
Current code (that does not use cursors):
$datasourceName = "big_database"
$sqlQuery = "SELECT * as 'millions_of_rows' FROM big_table"
$odbcConnection = new-object Data.Odbc.OdbcConnection
$odbcConnection.ConnectionString = "dsn=$datasourceName"
$odbcConnection.open()
$resultSet = (new-object Data.Odbc.OdbcCommand($sqlQuery, $odbcConnection)).ExecuteReader()
$table = new-object "System.Data.DataTable"
$table.Load($resultSet)
#/* Display results */
$table

How to query SQL Server using PowerShell

I have this code that I got from a website and it's connected to my SQL Server using window authentication but I'm not sure how can I choose a database and query some table?.
[Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") | out-Null
$s = new-object ('Microsoft.SqlServer.Management.Smo.Server') "server instance"
$s.ConnectionContext.LoginSecure=$true
$s.Databases | select name, size, status
If I run this code, it show me a list of databases but I want to choose a database called "LitHold" and query some table from that database inside.
For SMO like you have in your question, you can run queries that return data using ExecuteWithResults() like so:
$s = New-Object Microsoft.SqlServer.Management.Smo.Server "server instance"
$db = $s.Databases.Item("master")
$query = "SELECT * FROM [master].[sys].[databases] ORDER BY [name];"
$result = $db.ExecuteWithResults($query)
# Show output
$result.Tables[0]

keyword 'like' in my SQL statement in Poweshell is getting treated like an '=' sign

The like statement in my SQL query in powershell isn't producing the intended results. My 'like' statement is getting treated like an '=' sign.
for example
I have a table with the following values:
FieldNames
1. George Bush;George Foreman;Mary jones;
2. George Foreman;
3. George Foreman; Michael Smith;
4. Mary Jones;George Foreman
Variable:
$Expression = "George Foreman"
Three options I tried:
1.
Select FieldNames from table where FieldNames like '%$Expression%'
2.
Select FieldNames from table where FieldNames like '%$($Expression)%'
3.
Select FieldNames from table where FieldNames like '%George Foreman%'
I receive the same results for all three options (only row 2 returns). I would expect all the rows to return.
I can run this same query in SSMS and all rows return.
Has anyone ran across this problem or have any suggestions on how I can modify my select query to get all the rows using 'like'?
Formatted Powershell expression:
#Variables:
$Expression = "George Foreman"
$UserName = "UserName"
$password = "Password"
$Database = "Database"
$Server = "Server"
$Query="Select FieldNames from table where FieldNames like '%$Expression%' "
$ConnectionString = "Server=$Server ;User ID=$UserName; password=$password;
Integrated Security=True; database=$Database;"
$connection = New-Object System.Data.SqlClient.SqlConnection
$connection.ConnectionString = $connection
$connection.Open()
$command = $connection.CreateCommand()
$command.CommandText = $Query
$result = $command.ExecuteReader()
$connection.Close()

WHERE clause not working with blank values

In the code below I try to query an Excel file for a particular field "Username" Where there are blanks (= ''). But nothing gets returned to the data adapter.
The WHERE clause will return data for example if I specify a NOT LIKE 'thistext%', but again omits blanks.
Is there some way to better code the clause?
I have read there is an issue if fields are blank and need to be converted to DB NULL (or populated with a value) unsure how to do it.
$connection.ConnectionString = $connectstring
$connection.Open()
$objOleDbCommand.Connection = $connection
$objOleDbCommand.CommandText = "SELECT * FROM [$strSheetName] WHERE [Username] = ''"
$objOleDbAdapter.SelectCommand = $objOleDbCommand
$objOleDbAdapter.Fill($objDataTable)
$objDataTable | Export-Csv "C:\output\MyData_$dateandtime.csv" -NoTypeInformation
$connection.Close()
Try this instead to cover blanks and nulls.
Select * from [$strSheetName] where [Username] = '' OR [USERNAME] IS NULL
Note that this itself is not a powershell issue technically, you might encounter this same issue with other spreadsheets and databases.

Powershell and SQL Server - set nocount

I am writing a powershell function to retrieve a list of students from our database but the first item returned is always the number of records. I can't figure out a way to incorporate the set nocount on into the the script - any ideas?
The function so far is:
Function CheckMIS{
$Table = new-object System.Data.DataTable
$sqlConn = new-object System.Data.SqlClient.SqlConnection("Server=blah blah")
$adapter = new-object System.Data.SqlClient.SqlDataAdapter(
"select txtSchoolID,
intSystemStatus,
txtForename, txtSurname,
txtForm
from TblPupils
where intSystemStatus = 1 ",$sqlConn)
$adapter.Fill($Table)
$sqlConn.Close()
write-output $table
}
It returns a lovely table - but the first line is always the number of records first.
I just need to suppress that output.
You could catch the rowcount for later use.
$rowCount = $adapter.Fill($Table)
Or just ignore it.
$adapter.Fill($Table) | Out-Null
Adding "Set Nocount On; select txtSchoolID,"... didn't have any effect in my test.
You should be able to just add SET NOCOUNT ON to your SQL.
i.e. SET NOCOUNT ON select txtSchoolId, intSystemStatus,
txtForename, txtSurname,
txtForm
from TblPupils
where intSystemStatus = 1