我的表模式是这样的,
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);
最初,我的程序返回数据为
SELECT ID, EmpName, Age FROM @mytable;
处理完数据后,将网页发送为
[{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}]
如果我使用
SELECT ID, EmpName, Age
FROM @mytable
FOR JSON AUTO;
结果就像
[{"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}]
所以我需要得到的是相同的响应但没有列名,因为前端lib使用没有键的JSON数组。我希望我在结束时很清楚。谢谢。
试试这个:
SELECT STUFF
(
(
SELECT CONCAT(',{', ID, ', "', EmpName, '", ', age, '}')
FROM @mytable
FOR XML PATH(''), TYPE
).value('.', 'varchar(max)')
,1
,1
,'['
) + ']';
您可以使用“select to a variable”技巧来构建字符串。
declare @JsonesceString varchar(max);
select @JsonesceString = concat(@JsonesceString+','+char(10),'{',ID,',"',EmpName,'",',age,'}')
from @mytable
order by ID;
select concat('[',@JsonesceString,']') as Result;
返回值:
[{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}]