我正在尝试创建一个将json文件加载到表中的过程。如何以接受带有手动执行的文件名路径的方式创建过程?
这是我的代码:
CREATE PROCEDURE main.mainRun
@json NVARCHAR(max),
@path NVARCHAR(50)
AS
BEGIN
BEGIN TRY
SELECT @json = BulkColumn
FROM OPENROWSET (BULK @path, SINGLE_CLOB) as j;
if(ISJSON(@json)=1)
BEGIN
PRINT 'JSON File is valid'
INSERT INTO main.jsontable
SELECT GETDATE(),*
FROM OPENJSON(@json, '$.PersonDetails.Person')
with (
name varchar(50) '$.first_name',
surname varchar(50) '$.last_name',
email varchar(50) '$.email',
age varchar(50) '$.age',
balance varchar(50) '$.balance',
country varchar(50) '$.country',
registered varchar(50) '$.registered'
)
END
ELSE
BEGIN
PRINT 'JSON File is invalid'
END;
END TRY
BEGIN CATCH
PRINT ERROR_MESSAGE();
END CATCH
END;
GO
出于某种原因它不起作用,我写了它。
答案 0 :(得分:1)
问题在于您的OPENROWSET
查询。您需要使用Dynamic Sql将Path作为参数传递给OPENROWSET。有点像...
Declare @json NVARCHAR(MAX)
,@path NVARCHAR(50) = 'D:\TestFile.JSON'
,@Sql NVARCHAR(MAX)
SET @Sql = N' SELECT @json = BulkColumn
FROM OPENROWSET (BULK ''' + @path + ''', SINGLE_CLOB) as j;'
Exec sp_executesql @Sql
, N'@json NVARCHAR(MAX) OUTPUT'
, @json OUTPUT
-- Now use @json variable as you need to.
您的过程
CREATE PROCEDURE main.mainRun
@json NVARCHAR(max),
@path NVARCHAR(50)
AS
BEGIN
BEGIN TRY
Declare @Sql NVARCHAR(MAX);
SET @Sql = N'SELECT @json = BulkColumn
FROM OPENROWSET (BULK ''' + @path + ''', SINGLE_CLOB) as j;'
Exec sp_executesql @Sql
, N'@json NVARCHAR(MAX) OUTPUT'
, @json OUTPUT;
if(ISJSON(@json)=1)
BEGIN
PRINT 'JSON File is valid'
INSERT INTO main.jsontable
SELECT GETDATE(),*
FROM OPENJSON(@json, '$.PersonDetails.Person')
with (
name varchar(50) '$.first_name',
surname varchar(50) '$.last_name',
email varchar(50) '$.email',
age varchar(50) '$.age',
balance varchar(50) '$.balance',
country varchar(50) '$.country',
registered varchar(50) '$.registered'
)
END
ELSE
BEGIN
PRINT 'JSON File is invalid'
END;
END TRY
BEGIN CATCH
PRINT ERROR_MESSAGE();
END CATCH
END;
GO