3

My table schema is something like this,

DECLARE @mytable AS TABLE(ID INT, EmpName VARCHAR(10), Age INT);

INSERT INTO @mytable
VALUES
(1,     'a', 1),
(2,     'b', 2),
(3,     'c', 3),
(4,     'd', 4),
(5,     'e', 5),
(6,     'f', 6),
(7,     'g', 7),
(8,     'h', 8),
(9,     'i', 9),
(10,    'j', 10);

Initially, my procedure was returning with data as

SELECT ID, EmpName, Age FROM @mytable;

After processing the data, to the web page is sent as

[{1,"a",1},
{2,"b",2},
{3,"c",3},
{4,"d",4},
{5,"e",5},
{6,"f",6},
{7,"g",7},
{8,"h",8},
{9,"i",9},
{10,"j",10}]

If I use

SELECT ID, EmpName, Age
FROM @mytable
FOR JSON AUTO;

the result will be like

[{"ID":1,"EmpName":"a","Age":1},
 {"ID":2,"EmpName":"b","Age":2},
 {"ID":3,"EmpName":"c","Age":3},
 {"ID":4,"EmpName":"d","Age":4},
 {"ID":5,"EmpName":"e","Age":5},
 {"ID":6,"EmpName":"f","Age":6},
 {"ID":7,"EmpName":"g","Age":7},
 {"ID":8,"EmpName":"h","Age":8},
 {"ID":9,"EmpName":"i","Age":9},
 {"ID":10,"EmpName":"j","Age":10}]

So what I need to get is the same response but without column name, as front-end lib uses the JSON array without keys.

SQL Server version 2012 is used.

I hope I am clear on my end. Thanks.

3
  • @gotqn, Sorry, my home computer have sql server 2017 installed so I did not realize that it will not work on 2012 on which the project DB is. Any other options? Commented Feb 3, 2019 at 10:18
  • 1
    @Harsh . . . If you are using your home computer for development, you might want to learn about database compatibility levels: learn.microsoft.com/en-us/sql/t-sql/statements/…. Commented Feb 3, 2019 at 12:31
  • @GordonLinoff No, I am not using my home computer for development but since I was stuck with the problem in office so I was trying to solve it during weekend. About changing compatibility level, I will change that in my home PC's database. Thanks for the input. :) Commented Feb 3, 2019 at 12:42

2 Answers 2

4

Try this:

SELECT STUFF
(
    (
        SELECT CONCAT(',{', ID, ', "', EmpName, '", ', age, '}')
        FROM @mytable
        FOR XML PATH(''), TYPE
    ).value('.', 'varchar(max)')
    ,1
    ,1
    ,'['
) + ']';
Sign up to request clarification or add additional context in comments.

Comments

1

You could use the "select to a variable" trick to build the string.

declare @JsonesceString varchar(max);

select @JsonesceString = concat(@JsonesceString+','+char(10),'{',ID,',"',EmpName,'",',age,'}')
from @mytable
order by ID;

select concat('[',@JsonesceString,']') as Result;

Returns the value:

[{1,"a",1},
{2,"b",2},
{3,"c",3},
{4,"d",4},
{5,"e",5},
{6,"f",6},
{7,"g",7},
{8,"h",8},
{9,"i",9},
{10,"j",10}]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.