select Json related value and revert option

Mohammad Farook 161 Reputation points
2021-09-16T10:44:01.223+00:00

I Hi,
I want one more changes
i want display Name related ID

--Query1--
create table #CIDValue (Slno int,CID varchar(100))
INSERT INTO #CIDValue (Slno,CID) VALUES (67,'AAA'),(68,'BBB'),(69,'CCC')

create table #temp (ID INT,Details nvarchar(200))
INSERT INTO #temp (ID,Details) VALUES (1001,'[{"CID":"CCC"}]'),
(1002,'[{"CID":"AAA"},{"CID":"BBB"},{"CID":"CCC"}]'),
(1003,'[{"CID":"AAA"},{"CID":"BBB"},{"CID":"CCC"}])')

select * from #temp
drop table #temp,#CIDValue

--I want result like below
--ID Details
--1001 69
--1002 67,68,69
--1003 67,68,69

--Query2--
create table #CIDValue1 (Slno int,CID varchar(100))
INSERT INTO #CIDValue1 (Slno,CID) VALUES (67,'AAA'),(68,'BBB'),(69,'CCC')
create table #temp1 (ID INT,Details nvarchar(200))
INSERT INTO #temp1 (ID,Details) VALUES (1001,'69'),
(1002,'67,68,69'),
(1003,'67,68,69')

select * from #temp1
drop table #temp1,#CIDValue1
--I want result like below
--ID Detail
--1001 [{"CID":"CCC"}]
--1002 [{"CID":"AAA"},{"CID":"BBB"},{"CID":"CCC"}]
--1003 [{"CID":"AAA"},{"CID":"BBB"},{"CID":"CCC"}])

pls help

Developer technologies Transact-SQL
SQL Server Other
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 122.5K Reputation points
    2021-09-16T11:20:18.333+00:00

    Try these queries:

    select ID, string_agg(c.Slno, ',') as Details
    from #temp
    cross apply openjson( Details, '$') with ( v varchar(max) '$.CID' )
    inner join #CIDValue c on c.CID = v
    group by ID
    
    select ID, concat( '[', string_agg( j, ','), ']') as Details
    from #temp1
    cross apply string_split(Details, ',') s
    inner join #CIDValue1 c on c.Slno = s.value
    cross apply (values ((select c.CID as CID for json path, without_array_wrapper))) t(j)
    group by ID
    

    You can also discover that there are equivalent functions for STRING_AGG and STRING_SPLIT for old versions of SQL servers.

    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.