我想创建一个存储过程,它返回一行和一个额外的Bit列,说明该项是否在其他表中使用。
主要表:PrincipalId,RowA,RowB
表A:TableAId,PrincipalId,NameA
表B:TableBId,PrincipalId,NameB
TableC:TableCId,PrincipalId,NameC
如何比较PrincipalId以了解它是否正在使用并在最终选择中添加该结果?
感谢您的帮助。
ALTER PROCEDURE sp_available
@principalId int
AS
BEGIN
declare @available int
set @available = 1
IF EXISTS(select distinct PrincipalId from TableA where PrincipalId = @principalId
and select distinct PrincipalId from TableB where PrincipalId = @principalId
and select distinct PrincipalId from TableB where PrincipalId = @principalId)
BEGIN
set @available = 0
END
select RowA, RowB, @available as 'Available'
from Principal
where PrincipalId = @principalId
END
GO
exec sp_available 2
答案 0 :(得分:1)
您可以更改存储过程以返回bit
类型的输出参数。新定义如下。 @available
输出参数的默认值为0,即为false。此外,如注释中所述,您可以适当地更改过程名称以避免sp
的前缀,尽管我保留了原始名称。您可以在名称前添加应用程序首字母缩写词而不是sp。
另外,我已经在输出参数中返回了bit列,但是你可以将它作为row的一部分返回,如果这是你想要的。 如果您选择将其作为SELECT行的一部分返回,则可以从过程定义中删除输出参数。
ALTER PROCEDURE sp_available
@principalId int,
@available bit = 0 OUTPUT --returns true i.e. 1 if PrincipalID is in all tables else 0 i.e.false
AS
BEGIN
--start pessimistically by setting it to false
set @available = 0
IF EXISTS(select distinct PrincipalId from TableA where PrincipalId = @principalId)
AND EXISTS( select distinct PrincipalId from TableB where PrincipalId = @principalId)
AND EXISTS (select distinct PrincipalId from TableB where PrincipalId = @principalId)
BEGIN
set @available = 1
END
select RowA, RowB, @available as 'Available'
from Principal
where PrincipalId = @principalId
END
GO
declare @avail bit
exec sp_available 2, @avail output
--you can use the value of @avail after above call
答案 1 :(得分:1)
使用View
代替
CREATE VIEW viw_Principal AS
select
RowA, RowB,
CAST(CASE
WHEN EXISTS(SELECT * FROM TableA WHERE PrincipalId = Principal.PrincipalId) THEN 1
WHEN EXISTS(SELECT * FROM TableB WHERE PrincipalId = Principal.PrincipalId) THEN 1
WHEN EXISTS(SELECT * FROM TableC WHERE PrincipalId = Principal.PrincipalId) THEN 1
ELSE 0
END AS bit) as 'Available'
from Principal