我有3个表,其中ID可以在表1,表2,表3或表1和表3中.
我需要做的是将ID作为参数传递给存储过程,然后检查3个表并返回结果集,其中在3个表中的1个表中找到ID.
如果在表1和表3中都找到了ID,我需要返回表3的结果集.
所有表都不包含相同数量的列.我似乎无法正确构造这个.
到目前为止,这是我的存储过程:
ALTER PROCEDURE [dbo].[Login]
@userId varchar(20)
AS
BEGIN
SET NOCOUNT ON;
-- Customer Service User
IF EXISTS
(
SELECT cs.id,
first_name,
last_name,
logins.[email_address],
logins.[password],
phone,
shift,
manager,
location
FROM customer_service cs
INNER JOIN logins ON cs.id = logins.[id]
WHERE cs.id = logins.[id]
)
-- Marketing User
IF EXISTS
(
SELECT mktg.id,
first_name,
last_name,
logins.[email_address],
logins.[password],
phone,
manager,
location
FROM marketing mktg
INNER JOIN logins ON mktg.id = logins.[id]
WHERE mktg.id = logins.[id]
)
-- Remote User
IF EXISTS
(
SELECT ru.id,
first_name,
last_name,
logins.[email_address],
logins.[password],
manager,
location
FROM remote ru
INNER JOIN logins ON ru.id = logins.[id]
WHERE ru.id = logins.[id]
)
最佳答案 您希望存储的proc返回相同的列,无论数据来自哪个表,因此我将select语句组合在一起,并对不在给定表中的列名使用NULL.由于您只想在第三个表中不存在id时从第一个表返回记录,所以我将其添加到第一个select的where子句中:
ALTER PROCEDURE [dbo].[Login]
@userId varchar(20)
AS BEGIN SET NOCOUNT ON;
-- Customer Service User
SELECT
cs.id,
first_name,
last_name,
logins.[email_address],
logins.[password],
phone,
shift,
manager,
location
FROM customer_service cs
INNER JOIN logins ON cs.id = logins.[id]
WHERE cs.id = @userId
and not exists(select 1
from remote
where id = @userId)
union all
-- Marketing User
SELECT
mktg.id,
first_name,
last_name,
logins.[email_address],
logins.[password],
phone,
null as shift,
manager,
location
FROM marketing mktg
INNER JOIN logins ON mktg.id = logins.[id]
WHERE mktg.id = @userId
union all
-- Remote User
SELECT
ru.id,
first_name,
last_name,
logins.[email_address],
logins.[password],
null as phone,
null as shift,
manager,
location
FROM remote ru
INNER JOIN logins ON ru.id = logins.[id]
WHERE ru.id = @userId
end