简体   繁体   English

将 CSV 导入 SQL 服务器,其中一列是 JSON 数据

[英]Import CSV into SQL Server where one of the columns is JSON data

Is there a way of importing CSV data into a SQL Server table where one of the columns contains JSON data?有没有办法将 CSV 数据导入 SQL 服务器表,其中一列包含 JSON 数据?

An example CSV row might be the following:示例 CSV 行可能如下所示:

1,{"testId": 2, "testName":"Hello!"},3,4,5

When I try to import this using the following SQL, it picks up the JSON commas as being delimeters当我尝试使用以下 SQL 导入它时,它会选择 JSON 逗号作为分隔符

BULK INSERT TableName
FROM '<PathToCSV>'
WITH
(
  FIRSTROW = 1,
  FIELDTERMINATOR = ',',
  ROWTERMINATOR = '0x0A',
  TABLOCK
)

Is there a way of intelligently filtering them out as literal commas rather than delimeters similar to how Excel handles it?有没有一种方法可以智能地将它们过滤为文字逗号而不是分隔符,类似于 Excel 处理它的方式?

EDIT: Assume that its not feasible for me to edit the CSV's编辑:假设我编辑 CSV 不可行

You can use the CSV format specifier, along with FIELDQUOTE , to ensure that quoted values are not broken up if they contain commas.您可以将CSV格式说明符与FIELDQUOTE一起使用,以确保引用的值在包含逗号时不会被分解。 This only works on SQL Server 2017 onwards.这仅适用于 SQL Server 2017 及以后版本。

BULK INSERT SchoolsTemp
FROM '<PathToCSV>'
WITH
(
    FORMAT = 'CSV', 
    FIELDQUOTE = '"',
    FIRSTROW = 1,
    FIELDTERMINATOR = ',',
    ROWTERMINATOR = '0x0A',
    TABLOCK
)

As for the JSON itelf, if need be you can shred that after importing using OPENJSON .至于 JSON itelf,如果需要,您可以在使用OPENJSON导入后将其切碎。 For example例如

INSERT SomeTable (Column1, Column2, ParentId)
SELECT
  j.Column1,
  j.Column2,
  p.Id
FROM ParentTable p
CROSS APPLY OPENJSON(p.YourJson)
  WITH (
    Column1 int,
    Column2 varchar(100)
  ) j;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM