Share via

Select -> Json

ANB 181 Reputation points
2021-08-10T22:20:03.83+00:00

I have 2 tables:

a) Employees

EmployeeId: 1
EmployeeName: Maria

EmployeeId: 2
EmployeeName: Jose

EmployeeId: 3
EmployeeName: Junior

b) Products
Id: 1
ProductName: Book
EmployeeId: 1

Id: 2
ProductName: Pen
EmployeeId: 2

Id: 3
ProductName: Box
EmployeeId: 1

So I would like to have something like:
EmployeeId: 1, EmployeeName: Maria, Products: Book, Pen

But I will need convert it to Json to have something like:
{
employeeId: 1,
employeeName: Maria,
products {
productName: Book,
productName: Box
}
}

Whats the best way to do it ?
Thx

Developer technologies | Transact-SQL
Developer technologies | Transact-SQL

A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.

SQL Server | Other
SQL Server | Other

Additional SQL Server features and topics not covered by specific categories


2 answers

Sort by: Most helpful
  1. EchoLiu-MSFT 14,626 Reputation points
    2021-08-11T05:52:59.547+00:00

    Hi @AgaNeto-3704,

    Please refer to:

    CREATE TABLE Employees(EmployeeId INT,EmployeeName VARCHAR(15))  
    INSERT INTO Employees VALUES(1,'Maria'),(2,'Jose'),(3,'Junior')  
      
    CREATE TABLE Products(ID INT,ProductName VARCHAR(15),EmployeeId INT)  
    INSERT INTO Products VALUES(1,'Book',1),(2,'Pen',2),(3,'Box',1)  
      
    SELECT REPLACE(REPLACE(REPLACE((SELECT e.*,Products.ProductName  
    FROM Employees e  
    JOIN Products Products ON Products.EmployeeId = e.EmployeeId  
    WHERE e.EmployeeId=1  
    FOR JSON AUTO),'"',''),'[',''),']','')  
    

    Output:

    {EmployeeId:1,  
    EmployeeName:Maria,  
    Products:{ProductName:Book},{ProductName:Box}}  
    

    If you have any question, please feel free to let me know.

    Regards
    Echo


    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Was this answer helpful?

    1 person found this answer helpful.
    0 comments No comments

  2. Viorel 127K Reputation points
    2021-08-11T00:29:43.52+00:00

    Your example does not seem to be a valid JSON.

    Check the JSON output of this query:

    select e.*, products.ProductName
    from Employees e
    left join Products products on products.EmployeeId = e.EmployeeId
    for json auto
    

    Was this answer helpful?

    1 person found this answer helpful.
    0 comments No comments

Your answer

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