【问题标题】:Importing csv data to SQL using PowerShell使用 PowerShell 将 csv 数据导入 SQL
【发布时间】:2021-08-08 12:39:24
【问题描述】:

嗨,Interwebz 的 Glorius 人!

我带着一个不起眼的问题来找你(请放轻松,我在 PowerShell 方面还算不错,但我的 SQL 技能很少……:()

因此,我的任务是编写一个 powershell 脚本来导入数据(从多个 csv 文件到数据库),并且基于this(我对我的版本进行了大量修改),我取得了不错的进展。除了一个部分之外,所有的工作都很顺利:当我尝试插入值时(我创建了一种“映射文件”来将 csv 标头映射到数据),我似乎无法在值部分使用创建的字符串。所以这就是我所拥有的:

This is my current code for powershell(忽略 cmets)

This is a sample data csv

This is my mapping file

我想要的是替换

 VALUES(
            '$($CSVLine.Invoice_Status_Text)',  
            '$($CSVLine.Invoice_Status)', 
            '$($CSVLine.Dispute_Required_Text)',
            '$($CSVLine.Dispute_Required)', 
            '$($CSVLine.Dispute_Resolved_Text)',
            '$($CSVLine.Dispute_Resolved)',
            '$($CSVLine.Sub_Account_Number)',
            '$($CSVLine.QTY)',
            '$($CSVLine.Date_of_Service)',
            '$($CSVLine.Service)',
            '$($CSVLine.Amount_of_Service)',
            '$($CSVLine.Total)',
            '$($CSVLine.Location)',
            '$($CSVLine.Dispute_Reason_Text)',
            '$($CSVLine.Dispute_Reason)',

            '$($CSVLine.Numeric_counter)'
            );"

Part, for example with a string generated this way:

但是当我用 $valueString 替换长的 - 老实说,无聊的类型 - 值时,我得到了这种类型的错误:

Incorrect syntax was encountered while parsing '$($'.

不确定是否重要,但我的 PS 是 7.1

任何好的人可以就如何从我的文本文件中构建值提出好的建议...?

Ta, F.

【问题讨论】:

  • 尝试使用双引号 (") 而不是单引号 (')。单引号取字面上的任何内容,而双引号插入变量。所以在你的函数中做$valuesString = foreach ($string in $headers) { '"{0}"' -f ($placeholder -replace '__replaceme__' , $string) }
  • 不确定我是否正确,但我为此更改了代码: $headers = Get-Content -Path 'C:\Temp\SQL\ImportingCSVsIntoSQLv1\config\headers.txt' $headersString = $headers -join ', ' $placeholder = '$($CSVLine.__replaceme__)' $valuesString = @() foreach ($headers 中的$string){ $value = '"{0}"' -f ($placeholder -replace 'replaceme' , $string) $valuesString += $value } $valuesString = $valuesString -join ', ' 这会导致:"$($CSVLine.Numeric_counter)", "$( $CSVLine.Invoice_Status_Text)" .... 但我仍然收到错误... :(
  • 你说的SQL,是指SQL Server吗?一些 DBMS 产品附带一个实用程序,可以将 csv 文件读入表中。

标签: sql powershell


【解决方案1】:

正如评论的那样,将变量包装在单引号内会按照字面意思表示变量,因此您不会得到包含的值 (7957),而是像 $($CSVLine.Numeric_counter) 这样的字符串。

我不经常使用 SQL,但我想我会更改构造要插入的值的部分,如下所示:

# demo, read the csv file in your example
$csv = Import-Csv D:\Test\test.csv -Delimiter ';'

# demo, these are the headers (or better yet, the Property Names to use from the objects in the CSV) as ARRAY  
# (you use `$headers = Get-Content -Path 'C:\Temp\SQL\ImportingCSVsIntoSQLv1\config\headers.txt'`)
$headers = 'Invoice_Status_Text','Invoice_Status','Dispute_Required_Text','Dispute_Required',
           'Dispute_Resolved_Text','Dispute_Resolved','Sub_Account_Number','QTY','Date_of_Service',
           'Service','Amount_of_Service','Total','Location','Dispute_Reason_Text','Dispute_Reason','Numeric_counter'

# capture formatted blocks of values for each row in the CSV
$AllValueStrings = $csv | ForEach-Object {
    # get a list of values using propertynames you have in the $headers
    $values = foreach ($propertyName in $headers) {
        $value = $_.$propertyName
        # output the VALUE to be captured in $values
        # for SQL, single-quote the string type values. Numeric values without quotes
        if ($value -match '^[\d\.]+$') { $value }
        else { "'{0}'" -f $value }
    }
    # output the values for this row in the CSV
    $values -join ",`r`n"
}

# $AllValueStrings will now have as many formatted values to use 
# in the SQL as there are records (rows) in the csv
$AllValueStrings

使用您的示例,$AllValueStrings 会产生

'Ready To Pay',
1,
'No',
2,
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
7957

【讨论】:

  • 谢谢。这几乎可以让我到达我想要的地方,但我需要使用一个 csv 的值,许多的值。我的 $CSVImport = @() 实际上是这样创建的: $dataFiles = Get-ChildItem -Path $dataFolder *.csv foreach ($d in $dataFiles) { $CSVImport += Import-Csv $($d.FullName) -分隔符';'当我用 $csvImport 替换代码中的 $csv 时,它似乎没有导入任何东西 :( 我会尝试解决它,我相信我最终能够做到!
  • @krapulax 尝试像这样导入:$CSVImport = Import-Csv -Path (Get-ChildItem -Path $dataFolder -Filter '*.csv' -File).FullName -Delimiter ';'
  • 谢谢伙计。到目前为止,这并没有改变我的结果。稍后会再尝试一下,并会尝试找出我所缺少的。这是我的完整代码github.com/fabricesemti80/ImportingCSVsIntoSQLv1
猜你喜欢
  • 2021-09-22
  • 1970-01-01
  • 2019-09-20
  • 2015-06-14
  • 2023-02-01
  • 1970-01-01
  • 2015-10-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多