--------------------------------------------------- ----- 解析字符串函數(shù) ----- --------------------------------------------------- CREATE FUNCTION [dbo].[fn_split](@p_str VARCHAR(8000), @p_split VARCHAR(10)) RETURNS @tab TABLE(tid VARCHAR(2000)) AS BEGIN DECLARE @idx INT DECLARE @len INT SELECT @len = LEN(@p_split), @idx = CHARINDEX(@p_split, @p_str, 1) WHILE(@idx >= 1) BEGIN INSERT 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) END if(@p_str <> '') INSERT INTO @tab SELECT @p_str RETURN END;
------------------------------- -- 解析JSON字符串 -- ------------------------------- --p_jsonstr json字符串 --p_key 鍵 --返回p_key對應(yīng)的值 CREATE FUNCTION [dbo].[fn_parsejson](@p_jsonstr VARCHAR(8000), @p_key VARCHAR(200)) RETURNS VARCHAR(3000) AS BEGIN DECLARE @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; -- 聲明外層游標(biāo) SET @json_cur = CURSOR FOR SELECT tid FROM fn_split(@json, ','); OPEN @json_cur-- 打開游標(biāo)(外層游標(biāo)) FETCH NEXT FROM @json_cur INTO @tmprow-- 提取外層游標(biāo)行 WHILE(@@FETCH_STATUS = 0) BEGIN IF(@tmprow IS NOT NULL) BEGIN SET @i = 0; SET @jsonkey = ''; SET @jsonvalue = ''; DECLARE @str_cur CURSOR;-- 聲明內(nèi)層游標(biāo) SET @str_cur = CURSOR FOR SELECT tid FROM fn_split(@tmprow, ':');--第二次拆分后的游標(biāo)(內(nèi)層游標(biāo)) OPEN @str_cur -- 打開游標(biāo) FETCH NEXT FROM @str_cur INTO @tmpval-- 提取內(nèi)層游標(biāo)行 WHILE(@@FETCH_STATUS = 0) BEGIN IF(@i = 0) BEGIN SET @jsonkey = @tmpval END IF(@i = 1) BEGIN SET @jsonvalue = @tmpval END SET @i = @i + 1 FETCH NEXT FROM @str_cur into @tmpval-- 內(nèi)層游標(biāo)下移一行 END CLOSE @str_cur-- 關(guān)閉內(nèi)層游標(biāo) DEALLOCATE @str_cur -- 釋放內(nèi)層游標(biāo) IF(@jsonkey = @p_key) BEGIN SET @rtnVal = @jsonvalue END END FETCH NEXT FROM @json_cur INTO @tmprow-- 內(nèi)層游標(biāo)結(jié)束后,外層游標(biāo)下移一行 END CLOSE @json_cur-- 關(guān)閉外層游標(biāo) DEALLOCATE @json_cur-- 釋放外層游標(biāo) END RETURN @rtnVal END
創(chuàng)新互聯(lián)建站專注于陽信企業(yè)網(wǎng)站建設(shè),響應(yīng)式網(wǎng)站開發(fā),商城網(wǎng)站建設(shè)。陽信網(wǎng)站建設(shè)公司,為陽信等地區(qū)提供建站服務(wù)。全流程按需策劃設(shè)計(jì),專業(yè)設(shè)計(jì),全程項(xiàng)目跟蹤,創(chuàng)新互聯(lián)建站專業(yè)和態(tài)度為您提供的服務(wù)
使用示例:
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')