问题
Generate JSON in such a way that JSON for child table should have ARRAY_WRAPPER and JSON for parent table should NOT have ARRAY_WRAPPER and Query should be on PARENT1 table on column P1NAME in ('kumar,pathan'), so the output should have 2 rows
I have below mentioned tables
CREATE TABLE [dbo].[Z_PARENT1](
[P1id] [int] IDENTITY(1,1) NOT NULL,
[P1NAME] [varchar](50) NULL
)
CREATE TABLE [dbo].[Z_PARENT2](
[P2id] [int] IDENTITY(1,1) NOT NULL,
[P1id] [int] NOT NULL,
[P2NAME] [varchar](50) NULL
)
CREATE TABLE [dbo].[Z_CHILD](
[Cid] [int] IDENTITY(1,1) NOT NULL,
[P1id] [int] NOT NULL,
[CNAME] [varchar](50) NULL
)
INSERT INTO [dbo].[Z_PARENT1] ([P1NAME]) VALUES ('kumar'), ('pathan') , ('chris')
INSERT INTO [dbo].[Z_PARENT2] ([P1id],[P2NAME]) VALUES (1,'Mrs.kumar'), (2,'Mrs.pathan') , (3,'Mrs.chris')
INSERT INTO [dbo].[Z_CHILD] ([P1id],[CNAME]) VALUES (1,'A_kumar'),(1,'B_kumar'),(2,'X_pathan'),(2,'Y_pathan')
The query should be on PARENT1 table on column P1NAME in ('kumar,pathan'), so Query Output should have 2 rows,
Row1 should be like below
{
"PARENT1":{"P1id":1,"P1NAME":"kumar"},
"PARENT2":{"P2NAME":"Mrs.kumar"},
"CHILD":[{"Cid":1,"P1id":1,"CNAME":"A_kumar"},{"Cid":2,"P1id":1,"CNAME":"B_kumar"}]
}
Row2 should be like below
{
"PARENT1":{"P1id":2,"P1NAME":"pathan"},
"PARENT2":{"P2NAME":"Mrs.pathan"},
"CHILD":[{"Cid":3,"P1id":2,"CNAME":"X_pathan"},{"Cid":4,"P1id":2,"CNAME":"Y_pathan"}]
}
Please note that:(Important)
- I should be able to query on PARENT1 table on column P1NAME IN ('kumar,pathan') condition, so the output should have 2 rows
- Only child should have Arrays in JSON. (I mean ARRAY_WRAPPER) and parent1 & parent2 should NOT have Arrays (I mean WITHOUT_ARRAY_WRAPPER)
- There should be left join between parent and child because if the child has no rows at least parent JSON should be constructed.
- As parent1 & parent2 are master tables, there should be inner join on pid's
回答1:
If I follow you correctly, the following query will produce the result as you request in your question.
SELECT (SELECT TOP 1 IP1.P1id, IP1.P1NAME
FROM dbo.Z_PARENT1 IP1
WHERE IP1.P1id = P1.P1id
FOR JSON AUTO, WITHOUT_ARRAY_WRAPPER) AS PARENT1,
(SELECT TOP 1 IP2.P2NAME
FROM dbo.Z_PARENT2 IP2
WHERE IP2.P1id = P1.P1id
FOR JSON AUTO, WITHOUT_ARRAY_WRAPPER) AS PARENT2,
(SELECT *
FROM dbo.Z_CHILD IC
WHERE IC.P1id = P1.P1id
FOR JSON AUTO) AS CHILD
FROM [dbo].[Z_PARENT1] P1
FOR JSON AUTO
This query is not fully optimized, but it can be used as a potential solution.
It is just important to say, because you have multiple rows it cannot be an object, it should be array as a global result. You can easily expand this query and put where clause.
来源:https://stackoverflow.com/questions/65039335/json-for-multiple-parent-tables-and-one-child-table