How do I execute a SELECT query against a SQLServer database and iterate results using PowerShell

后端 未结 1 1831
误落风尘
误落风尘 2021-01-28 11:09

Say I have a table with 3 columns - \"Column1\", \"Column2\", and \"Column3\" - datatype is varchar(100) for all 3.

Using PowerShell, how do I connect to SQL Server and

相关标签:
1条回答
  • 2021-01-28 11:25

    Here's roughly how I'm doing it:

    $SqlServer = 'sql.example.com';
    $SqlDatabase = 'MyDB';
    
    $SqlConnectionString = 'Data Source={0};Initial Catalog={1};Integrated Security=SSPI' -f $SqlServer, $SqlDatabase;
    $SqlQuery = "SELECT Name FROM dbo.Person ORDER BY Name;";
    
    $SqlConnection = New-Object -TypeName System.Data.SqlClient.SqlConnection -ArgumentList $SqlConnectionString;
    $SqlCommand = $SqlConnection.CreateCommand();
    $SqlCommand.CommandText = $SqlQuery;
    
    $SqlConnection.Open();
    $SqlDataReader = $SqlCommand.ExecuteReader();
    
    #Fetch data and write out to files
    while ($SqlDataReader.Read()) {
        Write-Output $SqlDataReader['Name'];
    }
    $SqlConnection.Close();
    $SqlConnection.Dispose();
    

    If I remember right, I basically refactored the code from the MSDN example.

    For those wondering why I'm using SqlDataReader: Most of my scripts use SqlDataAdapter, but this one retrieves about 8,000 PDFs from a database so I wasn't really interested in calling SqlDataAdapter.Fill(). In exchange for holding shared locks on the table much longer than SqlDataAdapter.Fill() would, SqlDataReader.Read() keeps memory usage down to a manageable level for the client by fetching one record at a time.

    0 讨论(0)
提交回复
热议问题