Link to home
Start Free TrialLog in
Avatar of sqlagent007
sqlagent007Flag for United States of America

asked on

Need help writing the contents of System.Data.DataSet to a SQL server table

Please help with this simple script. I am trying to get a list of all user databases from a server, then write that list to a central table. So far I am able to query a remote SQL instance, and display the results on the screen. However I am struggling with how to write the values in System.Data.DataSet to a SQL Server table.

The table actually has 5 columns and allows null values. I only need to insert INSTANCE NAME and DATABASE NAME to the table.

Everything works up to line 19, but I am stuck on how to insert the data to a table.

# create the connection to the remote instance
$sqlConn = New-Object System.Data.SqlClient.SqlConnection
$sqlConn.ConnectionString = "Server=my_server;Integrated Security=true;Initial Catalog=my_db"
$sqlConn.Open()

#build cmd sting and run the command
$sqlcmd = New-Object System.Data.SqlClient.SqlCommand
$sqlcmd.Connection = $sqlConn
$query = "SELECT @@SERVERNAME as SQL_INST_NAME, [name] FROM sys.databases WHERE database_id > 4 AND [name] <> 'someOtherDB' "
$sqlcmd.CommandText = $query

#bind results to data adapter
$adp_rs = New-Object System.Data.SqlClient.SqlDataAdapter $sqlcmd
$data = New-Object System.Data.DataSet
$adp_rs.Fill($data) | Out-DataTable

#display data: this shows me what I expect to see
$data.Tables

#connect to other SQL instnace
$localConn = New-Object System.Data.SqlClient.SqlConnection
$localConn.ConnectionString = "Server=MyServer\MyInstance;Integrated Security=true;Initial Catalog=db"
$localConn.Open()

$bc = New-Object ("System.Data.SqlClient.SqlBulkCopy") $localConn
$bc.DestinationTableName = "dbo.table_name"
$bc.WriteToServer($adp_rs)
$localConn.Close()

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of DBAduck - Ben Miller
DBAduck - Ben Miller
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of sqlagent007

ASKER

Testing now...THANK YOU!
Thanks this worked great! My only question is what does the [0] do? When I looked at that I thought [0] specified the first column in the Data.Table. Clearly that is not the case because both columns got inserted. What does the [0] signify?

Thanks!
In my mind I was thinking I would need to do something like Data.Table([0],[1]).
When you use the DataAdapter.Fill( ) you are getting back a DataSet which contains an array of tables.

So to get the first table which is all that would be there would be to use

$data.Tables[0] -- which is just saying you want the first table and that is all.  Write to sql server does not accept a DataSet as an argument.
If you had 2 tables then you would have 2 calls to Write with $data.Tables[0] and $data.Tables[1]
Thank you!!!