--創建測試環境
Create Table 公司表(id Int, name Varchar(10))
Create Table 部门表(id Int, name Varchar(10), 公司id Int)
Create Table 职员表(id Int, name Varchar(10),公司id Int, 部门id Int)
Insert 公司表 Select 1, 'G1'
Union All Select 2, 'G2'
Union All Select 3, 'G2'
Insert 部门表 Select 1, 'B1', 1
Union All Select 2, 'B2', 1
Union All Select 3, 'B3', 2
Insert 职员表 Select 1, 'Z1', 1, 1
Union All Select 2, 'Z2', 1, 2
GO
--創建存儲過程
Create ProceDure SP_TEST(@id Int, @Result Varchar(100) Output)
As
If Not Exists(Select id From 公司表 Where id = @id)
Select @Result = 'none enterprise'
Else
Begin
If Exists(Select A.id From 公司表 A Left Join 部门表 B On A.id = B.公司id Where B.公司id Is Null And A.id = @id)
Select @Result = 'none depart'
Else
Begin
If Exists(Select A.id From 公司表 A Inner Join 部门表 B On A.id = B.公司id Where Not Exists(Select id From 职员表 Where 公司id = A.id And 部门id = B.id) And A.id = @id)
Select @Result = 'none employee'
Else
Select @Result = 'success'
End
End
GO
--測試
Declare @Result Varchar(100)
EXEC SP_TEST 5, @Result Output
Select @Result
EXEC SP_TEST 3, @Result Output
Select @Result
EXEC SP_TEST 2, @Result Output
Select @Result
EXEC SP_TEST 1, @Result Output
Select @Result
GO
--刪除測試環境
Drop Table 公司表, 部门表, 职员表
Drop ProceDure SP_TEST
--結果
/*
none enterprise
none depart
none employee
success
*/