2015-12-16 90 views
0

我有一個存儲過程是這樣的:明確SQL存儲過程?

IF @Active=0 
    select @rowCount=(select count(1) from [table] WHERE (GETDATE() BETWEEN StartTime AND EndTime) AND [email protected] 

IF @Active=1 
    select @rowCount=(select count(1) from [table] WHERE NOT(GETDATE() BETWEEN StartTime AND EndTime) AND [email protected] 

有沒有什麼辦法,使報表更加清晰?這樣

我做分頁:

參數:

@pageNum AS BIGINT, 
@pageSize AS BIGINT, 
@Active AS INT, 
@RowCount AS INT OUTPUT 

,其餘:

IF @Active=0 
BEGIN 
    WITH K AS 
    ( - SELECT [Id] 
     FROM [table] 
     WHERE not(GETDATE() BETWEEN StartTime AND EndTime) AND [email protected] ORDER BY [Id] 
     OFFSET (@pagenum - 1) * @pagesize ROWS FETCH NEXT @pagesize ROWS ONLY 
    ) 
    SELECT T.[Id],T.[Name] 
    FROM [table] 
    AS T 
     INNER JOIN K 
     ON T.Id = K.Id 

    ORDER BY T.Id; 

    select @rowCount=(select count(1) from [table] WHERE not(GETDATE() BETWEEN StartTime AND EndTime) AND [email protected] 
END 
IF @Active=1 
BEGIN 
    WITH K AS 
    ( 
     SELECT [Id] 
     FROM [table] 
     WHERE (GETDATE() BETWEEN StartTime AND EndTime) AND [email protected] 
     ORDER BY [Id] 
     OFFSET (@pagenum - 1) * @pagesize ROWS FETCH NEXT @pagesize ROWS ONLY 
    ) 
    SELECT T.[Id],T.[Name] 
    FROM [table] 
    AS F 
     INNER JOIN K 
     ON T.Id = K.Id 

    ORDER BY T.Id; 

    select @rowCount=(select count(1) from [table] WHERE (GETDATE() BETWEEN StartTime AND EndTime) AND [email protected] END 

和存儲過程看起來很長..... 所以我想知道是否有更好的方法來使它更好

+0

是鉅細無遺的兩種可能的罪名 - 即是它的意思是,如果你用'一旦調用這個@ Active'設置爲0,再次設置爲1,並將結果相加在一起,如果這兩個結果的總和與'select [COUNT(*)from [table]''相同?因爲目前情況並非如此。 –

回答

0

這可能會更清晰並且只涉及一個SELECT:

select @rowcount = case @active 
    when 0 then sum(case when GETDATE() BETWEEN StartTime AND EndTime then 1 else 0 end) 
    when 1 then sum(case when GETDATE() BETWEEN StartTime AND EndTime then 0 else 1 end) end 
from [table] 
where [email protected] 

或者從@Damien_The_Unbeliever這個建議甚至pithier(儘管可能不太清楚!):

select @rowcount = sum(case when GETDATE() BETWEEN StartTime AND EndTime then [email protected] else [email protected] end) 
from [table] 
where [email protected] 
+1

也許可以通過使用「1- @ active」和「0 + @ active」作爲內部case的兩個表達式來摺疊它。 –

+0

謝謝 - 已添加您的建議。 – strickt01

0
IF @Active=0 select @rowCount=(SELECT CASE 
    WHEN @Active=0 
     THEN select count(1) from [table] WHERE (GETDATE() BETWEEN StartTime AND EndTime) AND [email protected] 
    WHEN @Active=1 
     THEN select count(1) from [table] WHERE NOT(GETDATE() BETWEEN StartTime AND EndTime) AND [email protected] 

你可以讓你的問題更清楚了嗎?

0

不知道這是清晰的,但這裏的那略顯不足冗長的另一種方法:

SELECT @rowCount = COUNT(1) 
FROM [table] 
WHERE 
    ((GETDATE() BETWEEN StartTime AND EndTime) AND Active = @Active) 
    OR (NOT (GETDATE() BETWEEN StartTime AND EndTime) AND Active = @Active);