请考虑以下表格:
[Id: 1, Name: "A1"], [Id: 2, Name: "A2"], ... [Id: 100, Name: "A100"]
我需要Id< = 50的数据,带分页。所以我写了
select *
from data
where Id <= 50 order by Id 0 rows fetch next 10 rows only
然后我执行另一个查询
select count(1)
from data
where Id <= 50
然后我将这样的json返回给客户
{
count:50,
values:[{Id:1, Name:'A1'}, ..., {Id:10,Name:'A10'}]
}
如何在SQL Server 2016中使用 1 选择并仅往返数据包来创建json?
答案 0 :(得分:0)
这是有效的......你现在的目标是不清楚的。
DECLARE @X TABLE(Id INT)
INSERT @X SELECT 1
INSERT @X SELECT 2
INSERT @X SELECT 3
SELECT
*
FROM
@X
INNER JOIN(SELECT YourCount=COUNT(*) FROM @X)AS X ON 1=1
当filter子句已知时,这是一种更有效的方法。
DECLARE @X TABLE(Id INT)
INSERT @X SELECT 1
INSERT @X SELECT 2
INSERT @X SELECT 3
DECLARE @MyFilterCount INT = (SELECT COUNT(*) FROM @X WHERE 1=1)
SELECT
MyCount=@MyFilterCount
,*
FROM
@X
答案 1 :(得分:0)
我找到了解决方案。
select (select count(1) from data where Id <= 50) as total,
(select * from data where Id <= 50 order by Id 0 rows fetch next 10 rows only FOR JSON PATH) as values
FOR JSON PATH, WITHOUT_ARRAY_WRAPPER
结果为
{
count:50,
values:[{Id:1, Name:'A1'}, ..., {Id:10,Name:'A10'}]
}