sql server Json表达式解析函数

看到Json表达式, 在某些特殊情况下直接存json值。  下面取json表达式某项的值。

 

/*
取Json表达式值
参数: @code,@json
返回: @code 对应的值
eg.
@json='{"free":30,"first":1,"first fee":10,"per":30,"per fee":1.5}'
select dbo.UFJson('per',@json)
*/
create function [UFJson]
(
@code varchar(100),
@json nvarchar(2000))
returns nvarchar(500)
AS
BEGIN
    declare @codeindex as int
    declare @valueindex as int
    declare @endindex as int

    set @codeindex = charindex(@code,@json)
    --没有找到code项
    if (@codeindex = 0) return ''
    
    set @valueindex = charindex(':',@json,@codeindex)
    set @endindex = charindex(',',@json,@codeindex)    
    
    if (@endindex = 0) set @endindex = charindex('}',@json,@codeindex)    


    --格式不对 return ''
    if (@valueindex = 0 or @endindex = 0) return ''
        
    --正常返回
    return substring(@json,@valueindex+1,@endindex-@valueindex-1)
END

GO

posted @ 2013-08-16 14:16  pnglog  阅读(790)  评论(0编辑  收藏  举报