2011-09-02 70 views
2

我正在創建一個存儲過程,它根據查詢設置3個變量,我必須返回它們的MAX值。我想不使用臨時表而下面這樣做讓我Incorrect styntax near ')'SQL Server:是否有可能在不使用臨時表的情況下在SELECT語句中UNION兩個表?

SELECT MAX(PermissionID) 
FROM (SELECT @ContactPermission As PermissionID UNION ALL 
     SELECT @GroupPermission As PermissionID) 

我也曾嘗試

SELECT MAX((SELECT @ContactPermission UNION ALL SELECT @GroupPermission)) 

錯誤,我得到的錯誤Cannot perform an aggregate function on an expression containing an aggregate or a subquery.

我也有嘗試繞過變量並在子查詢中使用UNION ...

SELECT MAX(PermissionID) 
FROM (SELECT PermissionID 
     FROM PermissionContact 
     WHERE ContactID = @ContactID 
     UNION ALL 
     SELECT PermissionID 
     FROM PermissionGroup 
     WHERE GroupID = @GroupID) 

這也給出了Incorrect syntax near ')'

任何想法或建議?臨時表是我唯一的選擇嗎?

回答

3

你需要給你的派生表一個別名。

SELECT MAX(PermissionID) 
FROM (SELECT @ContactPermission As PermissionID UNION ALL 
     SELECT @GroupPermission As PermissionID) as T 
+0

如此簡單和快速...由於一噸,我將在數分鐘,所以當標記爲答案讓我。 – jon3laze

+3

+1也可以使用'SELECT MAX(PermissionID) FROM(VALUES(@ContactPermission, @GroupPermission))T(PermissionID)' –

1

或者只是使用一個case語句

Select Case When @ContactPermission > @GroupPermission 
     Then @ContactPermission Else @GroupPermission End PermissionID 

,或者

SELECT Case When c.PermissionID > g.PermissionId 
     Then c.PermissionID Else g.PermissionId End 
FROM PermissionContact c Cross Join PermissionGroup g 
Where c.ContactID = @ContactID 
    And g.GroupID = @GroupID 
相關問題