how to get jsonstring along columns in sql server

harinathu 6 Reputation points
2020-11-20T09:38:41+00:00

hi i have one doubt in sql server .
how to get json format filed using few columns and get columns also.

table : emp
id | name | sal | depno
1 | a |100 |`10
2 | b |200 |20

based on above data i want output like below :

id |name | sal | deptno |empjsonstring
1 | a | 100 |10 |{"id":1,"name":"a","sal":100,"deptno":10}
2 | b | 200 |20 |{"id":2,"name":"b","sal"200,"deptno":20}

i tried like below :
select * from emp for json path,include_null_values,without_arry_wrapper

but above query not give expect result.

could you please tell me how to write a query to achive this task in sql server

Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,637 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Viorel 117K Reputation points
    2020-11-20T09:49:33.49+00:00

    This seems to work:

    select *, (select id, [name], sal, depno for json path, include_null_values, without_array_wrapper) as empjsonstring
    from emp
    
    1 person found this answer helpful.
    0 comments No comments

  2. EchoLiu-MSFT 14,581 Reputation points
    2020-11-23T07:59:26.047+00:00

    Hi @harinathu

    I tested the Viorel-1 method and it worked.

        select *,(select id,name,sal,depno for json path, include_null_values, without_array_wrapper) empjsonstring  
        from emp  
    

    41778-image.png

    Regards
    Echo


    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.
    Hot issues November--What can I do if my transaction log is full?
    Hot issues November--How to convert Profiler trace into a SQL Server table

    0 comments No comments

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.