0

PersonTbl、UserTblの2つのテーブルを調べるストアドプロシージャを作成しています。最初にPersonTblでuserIDを検索し、userIDが存在する場合は、UserTblから電子メールアドレスを取得して両方を返します。ただし、IDがない場合は、他の2つのテーブル(PersonsPendingTbl、UsersPendingTbl)でIDと電子メールを検索してください。IDが再度見つからない場合は、null/nullを返します。これまでのところ、これは私が思いついたものですが、それがそれを書くための最良の方法であるかどうかはわかりません。おすすめの変更があれば教えてください。

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
4

2 に答える 2

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
于 2012-08-07T09:19:49.450 に答える
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
于 2012-08-07T09:32:38.840 に答える