我正在编写一个存储过程来查看两个表 PersonTbl、UserTbl。首先在 PersonTbl 中搜索用户 ID,如果用户 ID 存在,则从 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