標籤:sqlserver 解析json字串
-------------------------------------------------------- 解析字串函數 --------------------------------------------------------CREATE FUNCTION [dbo].[fn_split](@p_str VARCHAR(8000), @p_split VARCHAR(10))RETURNS @tab TABLE(tid VARCHAR(2000))ASBEGINDECLARE @idx INTDECLARE @len INTSELECT @len = LEN(@p_split), @idx = CHARINDEX(@p_split, @p_str, 1)WHILE(@idx >= 1)BEGININSERT INTO @tab SELECT LEFT(@p_str, @idx - 1)SELECT @p_str = RIGHT(@p_str, LEN(@p_str) - @idx - @len + 1), @idx = CHARINDEX(@p_split, @p_str, 1)ENDif(@p_str <> ‘‘) INSERT INTO @tab SELECT @p_strRETURNEND;
--------------------------------- 解析JSON字串 -----------------------------------p_jsonstr json字串--p_key 鍵--返回p_key對應的值CREATE FUNCTION [dbo].[fn_parsejson](@p_jsonstr VARCHAR(8000), @p_key VARCHAR(200)) RETURNS VARCHAR(3000)AS BEGINDECLARE @rtnVal VARCHAR(3000); DECLARE @i INT; DECLARE @jsonkey VARCHAR(200); DECLARE @jsonvalue VARCHAR(1000); DECLARE @json VARCHAR(8000); DECLARE @tmprow VARCHAR(2000); DECLARE @tmpval VARCHAR(2000); IF(@p_jsonstr IS NOT NULL)BEGIN SET @json = REPLACE(@p_jsonstr, ‘{‘, ‘‘); SET @json = REPLACE(@json, ‘}‘, ‘‘); SET @json = REPLACE(@json, ‘"‘, ‘‘);DECLARE @json_cur CURSOR; -- 聲明外層遊標SET @json_cur = CURSOR FOR SELECT tid FROM fn_split(@json, ‘,‘);OPEN @json_cur-- 開啟遊標(外層遊標)FETCH NEXT FROM @json_cur INTO @tmprow-- 提取外層遊標行WHILE(@@FETCH_STATUS = 0)BEGINIF(@tmprow IS NOT NULL)BEGINSET @i = 0;SET @jsonkey = ‘‘;SET @jsonvalue = ‘‘;DECLARE @str_cur CURSOR;-- 聲明內層遊標SET @str_cur = CURSOR FOR SELECT tid FROM fn_split(@tmprow, ‘:‘);--第二次拆分後的遊標(內層遊標)OPEN @str_cur -- 開啟遊標FETCH NEXT FROM @str_cur INTO @tmpval-- 提取內層遊標行WHILE(@@FETCH_STATUS = 0)BEGINIF(@i = 0) BEGINSET @jsonkey = @tmpvalENDIF(@i = 1)BEGINSET @jsonvalue = @tmpvalENDSET @i = @i + 1FETCH NEXT FROM @str_cur into @tmpval-- 內層遊標下移一行ENDCLOSE @str_cur-- 關閉內層遊標DEALLOCATE @str_cur -- 釋放內層遊標IF(@jsonkey = @p_key)BEGINSET @rtnVal = @jsonvalueENDENDFETCH NEXT FROM @json_cur INTO @tmprow-- 內層遊標結束後,外層遊標下移一行ENDCLOSE @json_cur-- 關閉外層遊標DEALLOCATE @json_cur-- 釋放外層遊標END RETURN @rtnVal END
使用樣本:
Select dbo.fn_parsejson(‘{"billPrice":"1.67","buyDate":"2009-12-30","currentStatus":"有租約","decoration":"精裝","empCode":"174999",","houseId":"F20BEBE259794C858C76122BCBACC71F","id":"36398","isAccompany":"0","isCollect":"1","isOnlyOne":"1","isShotProperty":"1","noCollectReason":"","parking":"0","propertyNo":"5885109","recordDate":"2017-06-08","recordRemark":"啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊"}‘,‘buyDate‘)
本文出自 “風之痕_雪虎” 部落格,請務必保留此出處http://snowtiger.blog.51cto.com/12931578/1942790
SQLServer 解析JSON字串