我有这样的查询:
(如您所见,我想检索总行数的50%或前100行等)
//@AllRowsSelectType is INT
SELECT TOP (
case @AllRowsSelectType
when 1 then 100 PERCENT
when 2 then 50 PERCENT
when 3 then 25 PERCENT
when 4 then 33 PERCENT
when 5 then 50
when 6 then 100
when 7 then 200
end
) ROW_NUMBER() OVER(ORDER BY [id]) AS row_num, a,b,c etc
为什么我会出现错误:“关键字'PERCENT'附近的语法不正确。”就行“当1 [...]”时
答案 0 :(得分:5)
TOP的语法是:
TOP (expression) [PERCENT]
[ WITH TIES ]
reserved keyword PERCENT不能包含在表达式中。相反,您可以运行两个不同的查询:一个用于何时需要PERCENT,另一个用于不需要时。
如果您需要将此作为一个查询,则可以运行两个查询并使用UNION ALL来组合结果:
SELECT TOP (
CASE @AllRowsSelectType
WHEN 1 THEN 100
WHEN 2 THEN 50
WHEN 3 THEN 25
WHEN 4 THEN 33
ELSE 0
END) PERCENT
ROW_NUMBER() OVER(ORDER BY [id]) AS row_num, a, b, c, ...
UNION ALL
SELECT TOP (
CASE @AllRowsSelectType
WHEN 5 THEN 50
WHEN 6 THEN 100
WHEN 7 THEN 200
ELSE 0
END)
ROW_NUMBER() OVER(ORDER BY [id]) AS row_num, a, b, c, ...
答案 1 :(得分:2)
您还混合了两种不同类型的用途。另一个是。
DECLARE @ROW_LIMT int
IF @AllRowsSelectType < 5
SELECT @ROW_LIMIT = COUNT(*)/@AllRowsSelectType FROM myTable -- 100%, 50%, 33%, 25%
ELSE
SELECT @ROW_LIMIT = 50 * POWER(2, @AllRowsSelectType - 5) -- 50, 100, 200...
WITH OrderedMyTable
(
select *, ROW_NUMBER() OVER (ORDER BY id) as rowNum
FROM myTable
)
SELECT * FROM OrderedMyTable
WHERE rowNum <= @ROW_LIMIT
答案 2 :(得分:0)
你可以这样做:
select top (CASE @FilterType WHEN 2 THEN 50 WHEN 3 THEN 25 WHEN 4 THEN 33 ELSE 100 END) percent * from
(select top (CASE @FilterType WHEN 5 THEN 50 WHEN 6 THEN 100 WHEN 7 THEN 200 ELSE 2147483647 END) * from
<your query here>
) t
) t
这可能更容易阅读。