【问题标题】:Specifying Text qualifier while importing a csv file to SQL Server DB在将 csv 文件导入 SQL Server DB 时指定文本限定符
【发布时间】:2018-08-29 14:45:14
【问题描述】:

我有一个逗号分隔的 csv 文件,问题是列内也有一个逗号。

TEXT,["pn","service"]

TEXT 位于一列,["pn","service"] 位于另一列。

如何使用文本限定符正确分隔列?

【问题讨论】:

  • 如果值为'["pn","service"]'(不是'"pn","service"'),那么您的文件不是有效的CSV 文件。如果您用来定义分隔符的字符可能/将在一个值中,那么您必须使用文本限定符。如果没有 out,那么文本值中的分隔符(在您的情况下为 ,)将被视为分隔符;这对于您拥有的任何 CSV 阅读器都是如此。如果无法更改,则需要在 SSIS 中使用脚本任务,并从头开始构建整个事物。
  • 另外,如果您可以将值更改为具有引号标识符,请不要使用'",因为这也在您的文本值中。如果可以的话,我建议您更改分隔符。我尝试使用管道(|)之类的东西,因为它们很少出现数据。

标签: sql-server csv import delimiter


【解决方案1】:

我最近不得不处理这个问题,并提出用标识符包装字段。我修改了下面的宏以用管道而不是引号分隔。超级用户帖子有更多选择。 查看https://support.microsoft.com/en-us/help/291296/procedure-to-export-a-text-file-with-both-comma-and-quote-delimiters-ihttps://superuser.com/questions/130592/how-do-you-force-excel-to-quote-all-columns-of-a-csv-file

根据@Larnu 的建议进行了更新——在导入某些数据文件之前,我使用它来重新包装它们以进行一次性加载。请注意直接在 excel 中打开 CSV...您可能会看到值发生变化。

Sub PipeCommaExport()
   ' Dimension all variables.
   Dim DestFile As String
   Dim FileNum As Integer
   Dim ColumnCount As Integer
   Dim RowCount As Integer

   ' Prompt user for destination file name.
   DestFile = InputBox("Enter the destination filename" _
      & Chr(10) & "(with complete path):", "Quote-Comma Exporter")

   ' Obtain next free file handle number.
   FileNum = FreeFile()

   ' Turn error checking off.
   On Error Resume Next

   ' Attempt to open destination file for output.
   Open DestFile For Output As #FileNum

   ' If an error occurs report it and end.
   If Err <> 0 Then
      MsgBox "Cannot open filename " & DestFile
      End
   End If

   ' Turn error checking on.
   On Error GoTo 0

   ' Loop for each row in selection.
   For RowCount = 1 To Selection.Rows.Count

      ' Loop for each column in selection.
      For ColumnCount = 1 To Selection.Columns.Count

         ' Write current cell's text to file with quotation marks.
         Print #FileNum, "|" & Selection.Cells(RowCount, _
            ColumnCount).Text & "|";

         ' Check if cell is in last column.
         If ColumnCount = Selection.Columns.Count Then
            ' If so, then write a blank line.
            Print #FileNum,
         Else
            ' Otherwise, write a comma.
            Print #FileNum, ",";
         End If
      ' Start next iteration of ColumnCount loop.
      Next ColumnCount
   ' Start next iteration of RowCount loop.
   Next RowCount

   ' Close destination file.
   Close #FileNum
End Sub

【讨论】:

  • 如果您发布链接,最好包含有效部分。链接可能会失效,但您帖子中的文字不会。
猜你喜欢
  • 1970-01-01
  • 2013-02-20
  • 1970-01-01
  • 2011-03-27
  • 1970-01-01
  • 1970-01-01
  • 2015-03-22
  • 2013-09-24
相关资源
最近更新 更多