Sql 2008R2 Max()

时间:2013-12-17 07:15:25

标签: sql sql-server-2008-r2

我有一个函数,我写了以下几行。

DECLARE @MaxLetterID BigInt;
DECLARE @MaxObserverLetterID BigInt;
DECLARE @MaxBillLetterID bigInt;

SET @MaxLetterID = (SELECT     MAX(LetterNO) AS Expr1
                    FROM         Lab
                    WHERE     (LetterNO BETWEEN @Min AND @Max));

SET @MaxObserverLetterID = (SELECT     MAX(LetterNO) AS Expr1
                    FROM         ObserverCoReq
                    WHERE     (LetterNO BETWEEN @Min AND @Max));

SET @MaxBillLetterID =(SELECT     MAX(LetterNO) AS Expr1
                    FROM         BillLetters
                    WHERE     (LetterNO BETWEEN @Min AND @Max));

SET @FinalID=MAX(@MaxLetterID,@MaxObserverLetterID,@MaxBillLetterID)
我是对的最后一行吗?我可以像这样使用Max功能吗?

1 个答案:

答案 0 :(得分:3)

不,你不能这样做。您需要一个SQL Server没有的greatest功能。但是这个

select @FinalID = max(c)  
from 
(
     select @MaxLetterID as c
     union  
     select @MaxObserverLetterID as c
     union
     select @MaxBillLetterID as c
) x

SQLFiddle demo