2009-07-26 13 views
6

Antes que nada permítanme agradecer a las personas que respondieron a mis preguntas anteriores. Ustedes son increíbles!Cómo enlazar Datareader y crear DataTable en Powershell

Aquí está mi pregunta: Me gusta consultar el servidor de sql Procedimiento almacenado y devolver un lector de datos. Sin embargo, quiero crear una tabla. Esa tabla la usaré para cargar Excel utilizando los nuevos comandos Powershell OpenXML. El código falla cuando intento construir DataTable. No creo que esté cargando correctamente el nuevo objeto "System.Object []". Aquí es lo que tengo hasta ahora:

$sqlConnection = new-object System.Data.SqlClient.SqlConnection "server=localhost;database=Demo;Integrated Security=sspi" 
$sqlConnection.Open() 

#Create a command object 
$sqlCommand = $sqlConnection.CreateCommand() 
$sqlCommand.CommandText = "EXEC Demo.usp_GetTableValueParameter_Data" 

#Execute the Command 
$sqlReader = $sqlCommand.ExecuteReader() 

#Parse the records 

$sqlReader | &{ begin{$values = new-object "System.Object[]" $sqlReader["Name"], $sqlReader["Level_Desc"], $sqlReader["Level"]} process {$_.GetValues($values); $datatable.Rows.Add($values)}} 

##$datatable | format-table -autosize 

# Close the database connection 
$sqlConnection.Close() 

#STARTING OPENXML PROCESS 
#---------------------------- 
$xlsFile = "C:\Temp\Data.xlsx" 
$datatable | Export-OpenXmlSpreadSheet -OutputPath $xlsFile -InitialRow 3 

Respuesta

3

no tengo idea de cómo hacer esto en powershell pero en .net lo haces de esta manera:

DataTable dt = new DataTable(); 
dt.Load(yourSqlReader); 
+1

Simplemente agregue signos de dólar ($) en los lugares correctos :-) – onupdatecascade

15

Traduciendo Mladen's answer en PowerShell es bastante sencillo :

$sqlConnection = new-object System.Data.SqlClient.SqlConnection "server=localhost;database=Demo;Integrated Security=sspi" 
$sqlConnection.Open() 

#Create a command object 
$sqlCommand = $sqlConnection.CreateCommand() 
$sqlCommand.CommandText = "EXEC Demo.usp_GetTableValueParameter_Data" 

#Execute the Command 
$sqlReader = $sqlCommand.ExecuteReader() 

$Datatable = New-Object System.Data.DataTable 
$DataTable.Load($SqlReader) 

# Close the database connection 
$sqlConnection.Close() 

#STARTING OPENXML PROCESS 
#---------------------------- 
$xlsFile = "C:\Temp\Data.xlsx" 
$datatable | Export-OpenXmlSpreadSheet -OutputPath $xlsFile -InitialRow 3 

sin embargo, si sólo necesitas una copia de DataTable, que no es necesario llamar a ExecuteReader en el comando, se puede crear un adaptador de datos y el uso que para llenar el DataTable:

$sqlConnection = new-object System.Data.SqlClient.SqlConnection "server=localhost;database=Demo;Integrated Security=sspi" 
$sqlConnection.Open() 

#Create a command object 
$sqlCommand = $sqlConnection.CreateCommand() 
$sqlCommand.CommandText = "EXEC Demo.usp_GetTableValueParameter_Data" 

$adapter = New-Object System.Data.SqlClient.SqlDataAdapter $sqlcommand 
$dataset = New-Object System.Data.DataSet 

$adapter.Fill($dataSet) | out-null 

# Close the database connection 
$sqlConnection.Close() 

$datatable = $dataset.Tables[0] 

#STARTING OPENXML PROCESS 
#---------------------------- 
$xlsFile = "C:\Temp\Data.xlsx" 
$datatable | Export-OpenXmlSpreadSheet -OutputPath $xlsFile -InitialRow 3 
Cuestiones relacionadas