我正在编写一个过程,希望通过使用mssql在游标中递归执行该功能。
以下代码中的函数ParseJson
是指How to parse JSON string recursively with openjson
PS。参考示例是递归版本,但在我的问题中,它是逐步解析。
这是我的函数ParseJson
topKey Key isTerminal Value
Book IssueDate 1 02-15-2019
Book Detail 0 { "Type":"Any Type", "Author":{ "Name":"Annie" , "Sex":"Female"}
Book Chapter 0 [{ "Section":"1.1", "Title":"Hello world." }, { "Section":"1.2", "Title":"Be happy." }]
Book Sponsor 0 ["A","B","C"]
每列isTerminal
的值是条件,
当isTerminal=0
时执行函数ParseJson
;
isTerminal=1
然后打印一些内容。
我正在创建一个过程以在sql游标中递归执行该函数。 该函数创建成功,但是执行失败。
create procedure CursorJson
@json nvarchar(max)
, @Type nvarchar(max)
, @isArray bit = 0
as
begin
set nocount on
declare
@TopKey nvarchar(4000)
, @Key nvarchar(4000)
, @IsType bit
, @IsList bit
, @isTerminal bit
, @Value nvarchar(4000)
--defind
declare myCursor cursor for
--dataset
select * from ParseJson(@json, @Type, @isArray)
--open
open myCursor
--run
fetch next from myCursor into
@TopKey nvarchar(4000)
, @Key nvarchar(4000)
, @IsType bit
, @IsList bit
, @isTerminal bit
, @Value nvarchar(4000)
while(@@fetch_status = 0)
begin
if @isTerminal = 0
begin
set @json = '{"' + @Key + '":' + @Value + '}'
exec CursorJson @json, @Key, @isList
end
else
begin
print 'insert...'
end
fetch next from myCursor into
@TopKey nvarchar(4000)
, @Key nvarchar(4000)
, @IsType bit
, @IsList bit
, @isTerminal bit
, @Value nvarchar(4000)
end
--close and deallocate
close myCursor
deallocate myCursor
return
end
declare @Type nvarchar(max)=N'Book'
declare
@json nvarchar(max)=N'{
"Book":{
"IssueDate":"02-15-2019"
, "Detail":{
"Type":"Any Type"
, "Author":{
"Name":"Annie"
, "Sex":"Female"
}
}
, "Chapter":[
{
"Section":"1.1"
, "Title":"Hello world."
}
,
{
"Section":"1.2"
, "Title":"Be happy."
}
]
, "Sponsor":["A","B","C"]
}
}'
--exec
exec CursorJson @json, @Type, 0
Program CursorJson,[Batch Start Line 0]已经存在名称为“ myCursor”的光标。
答案 0 :(得分:1)