sql-server - 使用SqlDataAdapter填充DataSet更改日期格式

标签 sql-server powershell datetime

我已经在网上搜索了所有内容,但无法找到针对我的问题的解决方案/指南。

我正在使用下面的脚本脚本(它是较大脚本的一部分)将多个SQL表导出为CSV。它使用SQL表中的数据填充数据集。

我遇到的问题主要与日期时间设置有关。例如,如果要使用导出向导将SQL表导出到CSV文件中。日期看起来与SQL中的日期完全相同,例如“2014-05-23 07:00:00.0000000”或“2014-05-23”。

但是,当我使用脚本时,它将日期时间的格式更改为“23/05/2014 07:00:00”或“23/05/2014 00:00:00”。我相信这与我的机器/ powershell session 的区域性设置有关。

cls

# Declare variables for connection and table to export
$Server     = 'server'
$Database   = 'database'
$Folder     = 'D:\Powershell Scripts\01_Export From SQL\Test Folder'
$Tablename1 = 'test'
$Tablename2 = ''

# Delcare Connection Variables
$SQLconnection = New-Object System.Data.SqlClient.SqlConnection
$SQLconnection.ConnectionString = "Integrated Security=SSPI;server=$Server;Database=$Database"

# Delcare SQL command variables
$SQLcommand = New-Object System.Data.SqlClient.SqlCommand 
$SQLcommand.CommandText = "SELECT [name] from sys.tables where [name] like '%$Tablename1%' and [name] like '%$Tablename2%' order by [name]"
$SQLcommand.Connection = $SQLconnection 

# Load up the Tables in a dataset
$SQLAdapter = New-Object System.Data.SqlClient.SqlDataAdapter 
$SQLAdapter.SelectCommand = $SQLcommand 
$DataSet = New-Object System.Data.DataSet 
$null = $SqlAdapter.Fill($DataSet)
$SQLconnection.Close()

"Time to Export`tRecords   `tFile Name"
"--------------`t-------   `t---------"

foreach ($Table in $DataSet.Tables[0])
{

    $stopwatch = [system.diagnostics.stopwatch]::StartNew()

    $FileExtractUTF8 = "$Folder\FromPSUTF8_$($Table[0]).csv"
    $SQLcommand.CommandText = "SELECT * FROM [$($Table[0])]"

    $SQLAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
    $SQLAdapter.SelectCommand = $SQLcommand 

    $DataSet = New-Object System.Data.DataSet 
    $Count = $SQLAdapter.Fill($DataSet)              
    $SQLconnection.Close() 

    $DataSet.Tables[0]  | Export-Csv $FileExtractUTF8 -NoTypeInformation -Encoding UTF8        

    $stopwatch.stop()

    $Time = "{0}" -f $stopwatch.Elapsed.ToString('mm\:ss\.fff')

    “{0,-14}`t{1,-10}`t{2}” -f $Time,$Count,$Table.name
}

主要目标是将数据从SQL导出到平面文件中,数据的显示方式与使用导出向导时的显示方式完全相同。

最佳答案

在脚本中更改默认的DateTime格式

在您的DataSet / DataTable中,日期以[DateTime]类型存在。导出为CSV时,需要将其转换为字符串,以便可以将其写入文件。如您所见,默认的字符串转换提供了如下输出:

[PS]> (get-date).ToString()
21/03/2017 17:52:26

该字符串的格式由您特定的全局化“文化”指定(如您所得出的那样)。它似乎是 DateTimeFormat ShortDatePattern LongTimePattern 属性的串联。

尝试改变失败本次 session 文化的人(即正在运行的PS主机)有很多帖子...
  • why-does-powershell-always-use-us-culture-when-casting-to-datetime

  • ...但是有可能使用如下所述的机制来更改脚本中的全局化文化:
  • powershell-changing-the-culture-of-current-session
  • Using-Culture function

  • 我怀疑您应该能够使用Using-Culture示例在脚本中包装Export-Csv行。

    但是要使用哪种文化?

    因此,您现在可以设置特定的区域性,但是任何先前存在的区域性都使用ISO8601(可排序)日期吗?或更具体的格式?似乎没有,所以您必须自己做!

    简而言之,您需要克隆一个现有的CultureInfo并更新DateTimeFormat,尤其是(至少)将ShortDatePattern更新为您想要的。这是一个例子,希望您能走对路。有两种功能,一种是克隆现有的CultureInfo,另一种是使用该线程的新区域性运行命令(Get-Date)。
    function New-CultureInfo {
      [CmdletBinding()]
      [OutputType([System.Globalization.CultureInfo])]
      param(
        [Parameter()]
        [System.Globalization.CultureInfo]
        $BaseCulture = [System.Globalization.CultureInfo]::InvariantCulture
      )
    
      $CultureInfo = ($BaseCulture).Clone()
    
      $CultureInfo.DateTimeFormat.ShortDatePattern = "yyyy'-'MM'-'dd"
      $CultureInfo.DateTimeFormat.LongTimePattern = "HH:mm:ss.fff"
    
      return $CultureInfo
    }
    
    function Test-DateFormat {
      [CmdletBinding()]
      [OutputType([System.DateTime])]
      param(
        [Parameter(Mandatory)]
        [System.Globalization.CultureInfo]
        $Culture
      )
    
      [System.Threading.Thread]::CurrentThread.CurrentUICulture = $Culture
      [System.Threading.Thread]::CurrentThread.CurrentCulture = $Culture
    
      (Get-Date).ToString()
    }
    

    使用示例:
    [PS]> $NewCulture = (New-CultureInfo)
    
    [PS]> Test-DateFormat $NewCulture
    2017-03-21 19:08:34.691
    

    现在,我无法针对与OP中的SQL问题类似的示例运行此命令,但是我很高兴将其全部解决。 ;-)

    关于sql-server - 使用SqlDataAdapter填充DataSet更改日期格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42915196/

    相关文章:

    wpf - Powershell 无法加载 Windows.Markup.XamlReader

    python - 如何删除像 July 1, 2019 这样的字符串

    php - 查找给定一天的当前月份的第一秒时间戳

    sql - 查看 SQL - 减去日期

    SQL Azure 重置自动增量

    sql-server - DATETIME 列上的 DATETIME 搜索谓词比字符串文字谓词慢得多

    sql - 从所有表和所有具有指定列名的数据库中查找列名 SQL Server

    c# - 使用 Microsoft.SqlServer.SMO 创建一个 Alter Stored Procedure sql 脚本?

    .net - 如何在 PowerShell 中更改列表框的字体大小

    java - 如何使用java对对象列表进行排序