2012-08-07 119 views
0

我正在編寫一個存儲過程以查看兩個表PersonTbl,UserTbl。首先在PersonTbl中搜索一個用戶標識,如果用戶標識在那裏從UserTbl獲得一個電子郵件地址並返回兩者。但是,如果該ID不在那裏,則搜索另外兩個表(PersonsPendingTbl,UsersPendingTbl)作爲ID和電子郵件。如果再次找到該ID,則返回null/nulls。到目前爲止,這是我想到的,但不知道這是寫它的最佳方式。讓我知道是否有任何改變,你會建議;如果第一個結果爲空,則查詢其他表

create PROCEDURE [dbo].[MyNewSP] 
@ID VARCHAR(MAX) 
AS 
    DECLARE @userID VARCHAR(50) 
    DECLARE @Email VARCHAR(100) 
    DECLARE @currentlyActive CHAR 
    BEGIN 

    SELECT 
     @userID = userTbl.ID , 
     @Email = personTbl.EMAIL, 
     @currentlyActive = 'Y' 
    FROM 
     personTbl 
     INNER JOIN userTbl ON personTbl.person_id = userTbl.person_id 
    WHERE 
     (userTbl.ID = @ID) 


    IF (@userID != @ID) --Check to see if null 
     BEGIN 
      SELECT @currentlyActive = 'N' 

      SELECT 
       upt.ID , 
       ppt.EMAIL, 
       @currentlyActive 
      FROM 
       PersonsPendingTbl ppt 
       INNER JOIN dbo.UsersPendingTbl upt ON ppt.person_id = upt.person_id 
      WHERE 
       (upt.ID = @ID) 
     END 
    ELSE 
     BEGIN 
      SELECT 
       @userID , 
       @Email , 
       @currentlyActive 
     END 

END 
+0

的'CREATE PROCEDURE'缺少 – Yaroslav 2012-08-07 08:32:15

+0

更正缺少一行。 – windowskm 2012-08-07 08:52:42

回答

1

將兩個結果合併,但始終選擇第一行。如果用戶註冊爲有效和無效的,它會返回一個有效:

Select * 
    from (
    SELECT userTbl.ID AS UID, personTbl.EMAIL as email, 'Y' as active 
     FROM personTbl 
     JOIN userTbl ON personTbl.person_id = userTbl.person_id 
     WHERE (userTbl.ID = @ID) 
    union all 
    SELECT upt.ID AS UID, ppt.EMAIL as email, 'N' as active 
     FROM PersonsPendingTbl ppt 
     INNER JOIN dbo.UsersPendingTbl upt ON ppt.person_id = upt.person_id 
     WHERE (upt.ID = @ID)) user 
    limit 0,1 
1

我不知道你的等待狀態,非待定表之間的值的唯一性,但是這應該是足夠接近,讓你去。

select 
case 
    when p.PersonId is null and pp.personPendingId is null then null 
    else userid 
end as userid, 
case 
    when p.PersonId is not null then p.email 
    when p.PersonId is null and pp.PersonPendingID is not null then pp.email 
    else null 
end as email, 
case 
    when p.PersonId is not null then 'Y' 
    when p.PersonId is null and pp.PersonPendingID is not null then 'N' 
    else null 
end as CurrentlyActive 
from userTbl u 
left join PersonTbl p on u.Person_id = p.PersonId 
left join userPendingTbl up on u.UserId = up.UserPendingId 
left join PersonPendingTbl pp on up.personPendingId = pp.PersonPendingID 
where u.UserId = @ID 
相關問題