SQLのJSON文字列から値を抽出したい。そうするための関数を書き始めましたが、「きっと他の誰かがすでにこれをやったのだろうか?」と思いました。SQL ServerにJSON_VALUE関数があるのを見て、とても興奮しました...しかし、2016年まで追加されていないことに気付いたときはとてもがっかりしました。:(
だから...私はこの関数の独自のバージョンを書いている最中です。最初はうまくいくように見えると確信していますが、時間の経過とともに完成するまで、エラーが発生することがあります。
しかし、誰かがすでにこれで有利なスタートを切って、私の最初のドラフトで確かに見落とすであろういくつかのねじれを解決したことを願っています...そしてここの誰かが私にそれを指摘できることを願っていますか?
まだ誰も提供できるものがないようですので、これまでに書いたコードを次に示します。多分それは私の靴の次の人を助けるでしょう。取得する値のタイプに応じて、別々の関数を使用することにしました。特筆すべきは、date関数は1970年からのミリ秒数である値を取得するためのものであり、decimal関数には値を引用符で囲むかどうかを指定するパラメーターがあることです。
create function [dbo].[GetJsonDateValue](@Key varchar(100), @data nvarchar(max))
returns datetime
as
begin
declare @keyIdx int = charindex(@Key, @data)
declare @valueIdx int = @keyIdx + len(@Key) + 2 -- +2 to account for characters between key and value
declare @termIdx int = charindex(',', @data, @keyIdx)
-- In case it's last item in an object
if @termIdx = 0
set @termIdx = charindex('}', @data, @keyIdx)
declare @valueLength int = @termIdx - @valueIdx
declare @secondsSince1970 bigint = cast(substring(@data, @valueIdx, @valueLength) as bigint) / 1000
declare @retValue datetime = dateadd(s, @secondsSince1970, '19700101')
return @retValue
end
GO
CREATE function [dbo].[GetJsonDecimalValue](@Key varchar(100), @data nvarchar(max), @quoted bit)
returns decimal(9,2)
as
begin
declare @keyIdx int = charindex(@Key, @data)
declare @valueIdx int = @keyIdx + len(@Key) + 2 -- +2 to account for characters between key and value
+ case when @quoted = 1 then 1 else 0 end -- +1 more for quote around value if present
declare @termIdx int = charindex(case @quoted when 1 then '"' else ',' end, @data, @valueIdx)
-- In case it's last item in an object and not quoted
if @quoted = 0 and @termIdx = 0
set @termIdx = charindex('}', @data, @keyIdx)
declare @valueLength int = @termIdx - @valueIdx
if @valueLength = 0
return null
declare @retValue decimal(9,2) = cast(substring(@data, @valueIdx, @valueLength) as decimal(9,2))
return @retValue
end
GO
CREATE function [dbo].[GetJsonStringValue](@Key varchar(100), @data nvarchar(max))
returns varchar(max)
as
begin
declare @keyIdx int = charindex(@Key, @data)
declare @valueIdx int = @keyIdx + len(@Key) + 3 -- +3 to account for characters between key and value
declare @termIdx int = charindex('"', @data, @valueIdx)
declare @valueLength int = @termIdx - @valueIdx
declare @retValue varchar(max) = substring(@data, @valueIdx, @valueLength)
return @retValue
end
GO
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加