我为公司的树制作了这样的存储过程
有2张桌子。 tb_Dept和tb_Company。 表格数据是这样的。
tb_dept
CompanyCode DeptCode DisplayName ParentDeptCode DeptEmail DisplayYN SortOrder
H101 1A07 RnD 1000 RnD@test.com Y 0
H101 1907 Solution 1000 Solution@test.com Y 0
H101 1A34 Management 1000 Management@test.com Y 0
H101 1000 CEO org ceo@test.com Y 0
tb_Company
CompanyCode CompanyName GIDCode
H101 TestIT 1000
K101 DevelopeIT 1001
S101 AnalysisIT 1024
首先是if-select语句,结果如下。
DeptCode DeptName HasSubDept DeptEmail CompanyCode CompanyName
H101 TestIT 0 H101 TestIT
我想添加此结果
DeptCode DeptName HasSubDept DeptEmail CompanyCode CompanyName
H101 CEO 0 H101 TestIT
所以,最后,首先是if- select语句结果是这样的。
DeptCode DeptName HasSubDept DeptEmail CompanyCode CompanyName
H101 TestIT 0 H101 TestIT
H101 CEO 0 H101 TestIT
是的,我知道它看起来很奇怪,但我必须这样做。
如何修改if语句或添加其他代码?
请有人帮助我。我的存储过程如下。
USE TestChart
GO
DECLARE @companyCode varchar(20)
, @parentDeptCode varchar(20)
, @isRelative bit
, @langCode varchar(20)
SELECT @companyCode = 'H101'
,@parentDeptCode = ''
,@isRelative = 0
,@langCode = 'ko'
IF @parentDeptCode IS NULL OR @parentDeptCode = ''
BEGIN
SELECT
CompanyCode AS DeptCode
, CompanyName AS DeptName
, dbo.uf_HasChildDept(CompanyCode) AS HasSubDept
, '' AS DeptEmail
, CompanyCode
, CompanyName
FROM dbo.tb_Company
WHERE CompanyCode = @companyCode
END
ELSE
BEGIN
SELECT
D.DeptCode
, ISNULL(D.DisplayName, '') AS DeptName
, dbo.uf_HasChildDept(D.DeptCode) AS HasSubDept
, D.DeptEmail
, C.CompanyCode
, C.CompanyName
FROM dbo.tb_Dept D WITH (NOLOCK)
INNER JOIN dbo.tb_Company C WITH (NOLOCK)
ON C.CompanyCode = @companyCode
WHERE D.ParentDeptCode = @parentDeptCode
AND D.DisplayYN = 'Y'
AND c.CompanyCode = d.CompanyCode
ORDER BY D.SortOrder
END
答案 0 :(得分:1)
您应该使用UNION ALL
。
如果需要,您可以在@parentDeptCode IS NULL OR @parentDeptCode = ''
子句中加入WHERE
条件。
SELECT
CompanyCode AS DeptCode
, CompanyName AS DeptName
, dbo.uf_HasChildDept(CompanyCode) AS HasSubDept
, '' AS DeptEmail
, CompanyCode
, CompanyName
FROM dbo.tb_Company
WHERE CompanyCode = @companyCode
UNION ALL
SELECT
D.DeptCode
, ISNULL(D.DisplayName, '') AS DeptName
, dbo.uf_HasChildDept(D.DeptCode) AS HasSubDept
, D.DeptEmail
, C.CompanyCode
, C.CompanyName
FROM dbo.tb_Dept D WITH (NOLOCK)
INNER JOIN dbo.tb_Company C WITH (NOLOCK) ON C.CompanyCode = D.CompanyCode
WHERE (ISNULL(@parentDeptCode, '') = '' AND D.ParentDeptCode = 'org') OR D.ParentDeptCode = @parentDeptCode)
AND D.DisplayYN = 'Y'
AND C.CompanyCode = @companyCode
ORDER BY D.SortOrder