我需要允许用户查询所有或部分记录。现在我这样做:
DECLARE @Limit INT = NULL
IF @Limit IS NULL SELECT @Limit = COUNT(ID) FROM vwNotifications
SELECT TOP (@Limit) ROW_NUMBER() OVER(ORDER BY Type, CreatedBy DESC) AS Row, Title
FROM vwNotifications
有没有办法可以在不使用COUNT
查询的情况下执行此操作?
答案 0 :(得分:5)
你有两个选择
如果它是0,那么1可以达到20亿 但是又一次..你真的想在一次拍摄中返回20亿行吗?
DECLARE @Limit INT = NULL
SELECT @Limit = COALESCE(@Limit, 200000000)
SELECT TOP (@Limit) ROW_NUMBER() OVER(ORDER BY Type, CreatedBy DESC) AS Row, Title
FROM vwNotifications
或做一个if else
DECLARE @Limit INT = NULL
IF @Limit IS NULL
SELECT ROW_NUMBER() OVER(ORDER BY Type, CreatedBy DESC) AS Row, Title
FROM vwNotifications
else
SELECT TOP (@Limit) ROW_NUMBER() OVER(ORDER BY Type, CreatedBy DESC) AS Row, Title
FROM vwNotifications
答案 1 :(得分:3)
假设您的表永远不会包含超过整数支持的行数(即主键是int
而不是bigint
,实际上可能是这样的:
DECLARE @Limit INT = NULL
IF @Limit IS NULL OR @Limit = 0
SET @Limit = 2147483647 -- Max Int
SELECT TOP (@Limit) ROW_NUMBER() OVER(ORDER BY Type, CreatedBy DESC) AS Row, Title
FROM vwNotifications
您的其他选项是if语句和两个查询..