如果top clause参数为null,有没有办法选择记录?
DECLARE @count FLOAT = 0;
Select @count = count from tblDetails
SELECT TOP(@count) from tblCompany
如果@count var为null,则我想从tblCompany中选择所有记录。
答案 0 :(得分:2)
DECLARE @count FLOAT = 0;
Select @count = count(1) from tblDetails
IF @count > 0
BEGIN
SELECT TOP(@intRecords) * from tblCompany
END
ELSE
BEGIN
SELECT * FROM tblCompany
END
如果你不想写两次查询 - 虽然只有一个会被执行,你可以试试这个:
DECLARE @count FLOAT = 0;
Select @count = count(1) from tblDetails
IF @count = 0
BEGIN
SET @intRecords = 100000 -- Or some number larger than the possible count
END
SELECT TOP(@intRecords) * from tblCompany
答案 1 :(得分:1)
当遇到像这样的情况时,我喜欢使用SQL Rank。
在下面的查询中,我假设您有一个ID
列,但您可以将其替换为任何其他列,以选择最佳列的标准:
DECLARE @count FLOAT = 0;
Select @count = count(*) from tblDetails
SELECT * FROM
(
SELECT
RANK () OVER
( ORDER BY ID ) 'Rank', -- <-- Assuming you have an ID column, replace with any other criteria for what will be considered as top...
*
FROM tblCompany
) tmp
WHERE (@count IS NULL) OR tmp.Rank <= @count
答案 2 :(得分:0)
我认为这样可行:
DECLARE @count AS INT ;
Set @count = (Select count(*) from tblDetails);
SELECT TOP(ISNULL(@count,5)) * from tblCompany