我正在尝试在SQL Server上执行以下查询:
DECLARE @Fid nvarchar(30)
DECLARE @max nvarchar(30)
DECLARE @min nvarchar(30)
DECLARE @Value nvarchar(30)
SET @Fid = '6'
SET @max = '317012'
SET @min = '317061'
SET @Value = 'ALL'
IF(@Value = 'ALL')
SELECT TOP 50 * FROM sample WHERE projectkey = 'Proj1'
IF(@Value = 'Next')
SELECT TOP 50 * FROM sample WHERE msgid <= @min AND projectkey = 'Proj1'
IF(@Value = 'Previous')
SELECT TOP 50 * FROM (SELECT TOP 50 * FROM sample WHERE projectkey = 'Proj1' AND msgid >= @max ORDER BY msgid ASC) as t ORDER BY msgid DESC
AND
fid = (CASE WHEN @Fid = 'ALL' THEN fid WHEN @Fid = '' THEN fid ELSE @Fid END)
在上面的查询中,我试图根据if条件执行select子句,并根据select子句给出的结果我想在子句条件作为过滤器的情况下应用于结果。我试图避免在每个if块中重复过滤器(即where子句)。我们如何实现或修改上述查询来实现这样的输出?
答案 0 :(得分:2)
试试这个
SELECT TOP 50 * FROM sample WHERE projectkey = 'Proj1' and ((@Value = 'ALL')
or (msgid <= @min and @Value = 'Next')
or (msgid >= @max and @Value = 'Previous'))
order by
case when @Value = 'Previous'
then
msgid
end
desc