我正在编写一个程序,希望使用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
程序CursorJson,[批处理开始行0]名称为“myCursor”的光标已存在。
“快速修复”将指定cursor is local:
declare myCursor cursor local for
但我会认真地重新审视你是否可以通过使用recursive CTE来实现你想要做的事情。