2013-07-28 20 views
0

我有以下DB模式:SQL查詢動態選擇不使用IF..THEN

enter image description here

用戶表存儲登錄在該領域的用戶「overridetemplate」是一個布爾值,讓我們知道,如果我們得到用戶安全模板信息或用戶覆蓋信息。

user_access表將用戶關聯到security_template(如用戶角色)。

security_template表具有安全模板信息(例如:電力用戶等)

security_template_exception擁有所有與模板的訪問權限(例如動作:與接入類型「insert_user」「 FullAccess「,」delete_user「和accesstype」Deny「)

所以這樣用戶有一個角色或安全模板,該模板有一堆帶有accesstype的」操作「給該用戶。

然後,我有一個額外的表,user_override_template,這是爲覆蓋安全模板創建,然後你可以分配indiviual操作權限用戶,而不會影響一個完整的安全模板。

只有3種類型的「接入類型:‘中。FullAccess’,‘只讀’和‘拒絕’

眼下,帶來了安全操作的訪問查詢如下:

SELECT 
         ste.[objectid], ste.[accesstype] 
        FROM 
         [user] AS u 
         JOIN [users_access] AS ua ON u.[userid] = ua.[userid] 
         JOIN [security_template] AS st ON ua.[templateid] = st.[templateid] 
         JOIN [security_templates_exceptions] AS ste ON st.[templateid] = ste.[templateid] 
        WHERE 
         su.[userid] = @userid 

查詢的結果是這樣的:

enter image description here

所以,我需要的是depeding場上「overridetemplate」我應該從「user_override_template」或「security_template_exception」獲取訪問信息。

如何做到這一點不使用(我想這樣做在一個單一的選擇)任何線索:

IF @overridetemplate = 1 
BEGIN 

END 
ELSE 
BEGIN 

END 

回答

0

你兩個連接和select子句中選擇您想要的:

SELECT (case when @UseSecurityTemplate = 'Y' then ste.[objectid] 
      else uto.objectid 
     end) as objectid 
     (case when @UseSecurityTemplate = 'Y' then ste.[accesstype] 
      else uto.accesstype 
     end) as AccessType 
FROM [user] AS u 
    LEFT JOIN [users_access] AS ua ON u.[userid] = ua.[userid] 
    LEFT JOIN [security_template] AS st ON ua.[templateid] = st.[templateid] 
    LEFT JOIN [security_templates_exceptions] AS ste ON st.[templateid] = ste.[templateid] 
    LEFT JOIN [user_override_template] AS uot ON ua.[templateid] = uot.[templateid] 
WHERE su.[userid] = @userid; 

我將連接切換到left outer join,以防止在沒有行時發生不必要的過濾。

+0

它不工作,它返回成千上萬的行..順便說一句,user_override_template沒有templateid列 – VAAA