sql server - Build json with variable key / json_modify variable 2nd parameter -
suppose have
create schema tmp go create table tmp.properties ( parentid uniqueidentifier not null, propertyname nvarchar(20) not null, propertyvalue nvarchar(100) null, primary key (parentid,propertyname) ) go create table tmp.fulldata ( parentid uniqueidentifier not null, properties nvarchar(max) null, primary key (parentid) ) go declare @id1 uniqueidentifier = 'f1935d6a-d5a6-4fa1-acf4-ba3858804cec', @id2 uniqueidentifier = 'f1935d6b-d5a6-4fa1-acf4-ba3858804cec' insert tmp.properties values (@id1, 'firstname', 'luke'), (@id1, 'lastname', 'skywalker'), (@id2, 'firstname', 'han'), (@id2, 'lastname', 'solo')
please consider that:
- properties dynamically created , cannot know in advance propertynames
- at moment parents table contains 1m , properties table contains 23m records
how can fill tmp.fulldata with:
parentid properties ------------------------------------ ------------------------------------------------ f1935d6a-d5a6-4fa1-acf4-ba3858804cec { "firstname": "luke", "lastname": "skywalker" } f1935d6b-d5a6-4fa1-acf4-ba3858804cec { "firstname": "han", "test1": "solo" }
i tried
insert tmp.fulldata (parentid, properties) select distinct parentid, '{}' tmp.properties update f set properties = json_modify(properties, 'append $.' + p.propertyname, p.propertyvalue) tmp.fulldata f cross join tmp.properties p
but know/imagine
msg 13610, level 16, state 2, line 39 argument 2 of "json_modify" must string literal.
any other option? in advance
skip update , insert directly tmp.fulldata:
insert tmp.fulldata (parentid, properties) select parentid ,'{' + stuff(( select ',' + '"' + propertyname + '":"' + propertyvalue + '"' tmp.properties a.parentid = p.parentid xml path(''), type ).value('.', 'varchar(max)'), 1, 1, '' ) + '}' properties tmp.properties p group parentid;
Comments
Post a Comment