我想从this tutorial的行中读取Azure Blob存储中的大量JSON文件(约1000个)并将它们插入到Azure SQL数据库SQL表中,但要从文件中读取JSON比内联。要清楚:我希望每个文件都作为一个字符串读取,该字符串成为表中的单个NVARCHAR(max)条目。这似乎应该很简单,但是我不知道该怎么做。
下面是我的代码,在我注释的行上会产生错误“'(')附近的语法不正确。每个JSON文件只是一个字典,所有相同的键都沿着
{“ D”:“ 0.980287579”,“ B”:“ 0.679793971”,“ C”:“ 0.217004033”,“ A”:“ 0.675980258”}
IF OBJECT_ID(N'dbo.testJSON', N'U') IS NOT NULL
DROP TABLE dbo.testJSON
GO
CREATE TABLE dbo.testJSON (
rowID smallint NOT NULL PRIMARY KEY,
jsonData nvarchar(max)
)
GO
ALTER TABLE dbo.testJSON
ADD CONSTRAINT [Check for JSON] CHECK (ISJSON(jsonData)=1)
GO
DECLARE @i INT = 1
DECLARE @json AS NVARCHAR(MAX)
DECLARE @file AS VARCHAR(4000)
WHILE @i < 1000
BEGIN
SET @file = 'JSONfile' + CAST(@i AS VARCHAR(5)) + '.json'
-- Line below doesn't work
SELECT @json = BulkColumn FROM OPENROWSET(BULK(@file), SINGLE_CLOB) AS j
-- Line above doesn't work
INSERT INTO dbo.testJSON (rowID, jsonData) VALUES (@i, @json)
set @i = @i + 1
END
GO
感谢大家的帮助!
答案 0 :(得分:0)
我将向读者介绍this问题,该问题的短语比我好。您必须使用动态SQL在OPENROWSET中插入变量。工作代码为:
IF OBJECT_ID(N'dbo.testJSON', N'U') IS NOT NULL
DROP TABLE dbo.testJSON
GO
CREATE TABLE dbo.testJSON (
rowID smallint NOT NULL PRIMARY KEY,
jsonData nvarchar(max)
)
GO
ALTER TABLE dbo.testJSON
ADD CONSTRAINT [Check for JSON] CHECK (ISJSON(jsonData)=1)
GO
DECLARE @i INT = 1
DECLARE @numObservations INT = 1000
DECLARE @json NVARCHAR(MAX)
DECLARE @file VARCHAR(4000)
DECLARE @sql VARCHAR(4000)
WHILE @i <= @numObservations
BEGIN
SET @file = 'testJSON' + CAST(@i AS VARCHAR(5)) + '.json'
SET @sql = N'INSERT INTO dbo.testJSON (rowID, jsonData)
SELECT ' + CAST(@i AS VARCHAR(5)) + ', * FROM OPENROWSET(BULK ''' + @file + ''', DATA_SOURCE = ''AzureBlobStorage'', SINGLE_CLOB) as x'
EXEC(@sql)
SET @i = @i + 1
END
GO