SQL递归udf总是返回null
Posted
技术标签:
【中文标题】SQL递归udf总是返回null【英文标题】:SQL recursive udf always returns null 【发布时间】:2017-09-28 03:22:30 【问题描述】:Create Table Employees
(
Employee varchar(10),
Manager varchar(10)
);
Insert into Employees
values
('Charlie',null),
('Peter','James'),
('Elai',null),
('Graham','Emanuel'),
('Amanda','Charlie'),
('Sen','Graham'),
('Emanuel',null),
('James','Amanda'),
('Elai',null),
('Victor','Elai');
“员工”表上方包含员工和员工的经理姓名。尝试使用以下函数检索员工的逗号分隔层次结构时,结果始终为空。
例如:
员工'Victor'
,层次结构/结果应为"Victor, Elai"
。
谁能指出我在 UDF 下面做错了什么。
Create Function EmployeeHierarchy(@employeeName varchar(20))
Returns varchar(100)
AS
Begin
Declare @commaSeparatedHierarchy varchar(100);
Declare @manager varchar(20);
if(@employeeName is not null)
Begin
Select @manager=Manager from Employees where Employee=@employeeName;
Set @commaSeparatedHierarchy=dbo.EmployeeHierarchy(@manager)+','+@manager;
End
return @commaSeparatedHierarchy;
End;
【问题讨论】:
测试数据加1 【参考方案1】:首先,您不想将其创建为标量函数。它们的性能是可怕的任何你创建的 udf,应该被创建为一个内联表值函数。以下应该可以满足您的需求...
-- the test data...
USE tempdb;
GO
IF OBJECT_ID('tempdb.dbo.Employee', 'U') IS NOT NULL
DROP TABLE dbo.Employee;
CREATE TABLE dbo.Employee (
Employee varchar(10),
Manager varchar(10)
);
INSERT dbo.Employee (Employee, Manager) VALUES
('Charlie',null),
('Peter','James'),
('Elai',null),
('Graham','Emanuel'),
('Amanda','Charlie'),
('Sen','Graham'),
('Emanuel',null),
('James','Amanda'),
('Elai',null),
('Victor','Elai');
SELECT * FROM dbo.Employee e;
iTVF 代码...
CREATE FUNCTION dbo.EmployeeHierarchy
(
@employeeName varchar(20)
)
RETURNS TABLE WITH SCHEMABINDING AS
RETURN
WITH
cte_Recur AS (
SELECT
CSH = CAST(CONCAT(e.Employee, ', ' + e.Manager) AS VARCHAR(1000)),
e.Manager,
NodeLevel = 1
FROM
dbo.Employee e
WHERE
e.Employee = @employeeName
UNION ALL
SELECT
CSH = CAST(CONCAT(r.CSH, ', ' + e.Manager) AS VARCHAR(1000)),
e.Manager,
NodeLevel = r.NodeLevel + 1
FROM
dbo.Employee e
JOIN cte_Recur r
ON e.Employee = r.Manager
WHERE
e.Manager IS NOT NULL
)
SELECT
commaSeparatedHierarchy = MAX(r.CSH)
FROM
cte_Recur r;
GO
示例执行...
SELECT
eh.commaSeparatedHierarchy
FROM
dbo.EmployeeHierarchy('peter') eh;
...结果...
commaSeparatedHierarchy
------------------------------
Peter, James, Amanda, Charlie
【讨论】:
谢谢你,杰森。以上是关于SQL递归udf总是返回null的主要内容,如果未能解决你的问题,请参考以下文章
java.sql.Connection createArrayOf() 总是返回 null
我的 SQL 函数有啥问题,当我尝试在 C# 中检索它的值时它总是返回 null?