我正在编写一个存储过程来查看两个表PersonTbl,UserTbl。首先在PersonTbl中搜索userID,如果userID在那里,则从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 :(得分: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
答案 1 :(得分: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