使用POWERSHELL从SQL导出,其中输出包含NULLS

时间:2015-03-02 11:01:40

标签: sql-server powershell

我使用下面的POWERSHELL脚本将SQL表的内容导出到.csv。它一直运作良好,不幸的是它失败了,因为这个表现在已经添加了一些NULLS。

有没有办法修改它以允许它传递NULLS,或者最好修改基础表。

$server = "sqlmtest"
$database = "mi_lookups"
$query = "SELECT * FROM [dbo].[SQLMtest-BIS-BUS-BPS_system_agent_lookup]"

$extractFile = @"
G:\system_Lookup_Tables\system_agent_lookup.csv
"@


$connectionTemplate = "Data Source={0};Integrated Security=SSPI;Initial Catalog={1};"
$connectionString = [string]::Format($connectionTemplate, $server, $database)
$connection = New-Object System.Data.SqlClient.SqlConnection
$connection.ConnectionString = $connectionString

$command = New-Object System.Data.SqlClient.SqlCommand
$command.CommandText = $query
$command.Connection = $connection

$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $command
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$connection.Close()


$DataSet.Tables[0] | Export-Csv $extractFile

谢谢。

2 个答案:

答案 0 :(得分:1)

谢谢大家(@Paul在评论中提出了这一点)。为解决此问题,我使用ISNULL()将项目包装在原始选择中。

$query = "SELECT [l].client_key, ISNULL([l].client_name) FROM [dbo].[test] AS [l]"

不是一个特别优雅的解决方案,但它解决了这个问题。

答案 1 :(得分:0)

只是关于PowerShell语法的评论:不要让它变得更加困难。

here-string是没有意义的,只需制作一个常规字符串:

$extractFile = "G:\system_Lookup_Tables\system_agent_lookup.csv"

$connectionTemplate = "Data Source={0};Integrated Security=SSPI;Initial Catalog={1};"
$connectionString = [string]::Format($connectionTemplate, $server, $database)
$connection = New-Object System.Data.SqlClient.SqlConnection
$connection.ConnectionString = $connectionString

可以像这样重写:

$connection = New-Object System.Data.SqlClient.SqlConnection("Data Source=$server;Integrated Security=SSPI;Initial Catalog=$database;")

这个

$command = New-Object System.Data.SqlClient.SqlCommand
$command.CommandText = $query
$command.Connection = $connection
像这样:

$command = New-Object System.Data.SqlClient.SqlCommand($query, $connection)

与SqlDataAdapter相同。