将null传递给CTE以将所有记录作为默认值?

时间:2010-12-13 18:38:52

标签: sql-server-2005

我将CTE作为UDF,并且我试图让它采用默认值为no,因为返回的结果应该是一切。

我想将其称为默认值:

select * from fnGetEmployeeHierarchyByUsername

我的UDF / CTE是:

alter FUNCTION [dbo].[fnGetEmployeeHierarchyByUsername]   
(      
  @AMRSNTID varchar(100) = null  
)    
RETURNS TABLE    
AS    
RETURN    
(    
  WITH yourcte AS    
  (    
    SELECT EmployeeId, ManagerAMRSNTID, ManagerID, AMRSNTID, FullName, 0 as depth--, Name    
    FROM Employees    
    WHERE AMRSNTID = @AMRSNTID
    UNION ALL    
    SELECT e.EmployeeId, e.ManagerAMRSNTID, e.ManagerID, e.AMRSNTID, e.FullName, y.depth+1 as depth--, e.Name    
    FROM Employees e    
    JOIN yourcte y ON e.ManagerAMRSNTID = y.AMRSNTID
  )    
SELECT EmployeeId, ManagerID, AMRSNTID, FullName, depth--, Name    
FROM yourcte    
)  

我怎么能让它像这样工作?

2 个答案:

答案 0 :(得分:0)

在UDF中尝试此操作

WHERE AMRSNTID = ISNULL(@AMRSNTID, AMRSNTID)

然后这样称呼它

select * from fnGetEmployeeHierarchyByUsername(DEFAULT)
--or
select * from fnGetEmployeeHierarchyByUsername(NULL)

编辑:无需查看数据或层次结构的外观,您需要添加一个OPTION子句 如果它永远运行,你在某处有一个循环链接

select * from fnGetEmployeeHierarchyByUsername(DEFAULT) OPTION (MAXRECURSION 0)

注意:您不能在UDF中使用OPTION

Edit2:我的错误抱歉。您需要从没有经理的员工开始(即从顶部开始)

这样的东西
WHERE
    (@AMRSNTID IS NOT NULL AND AMRSNTID = @AMRSNTID)
    OR
    (@AMRSNTID IS NULL AND ManagerAMRSNTID IS NULL)

答案 1 :(得分:0)

alter FUNCTION [dbo].[fnGetEmployeeHierarchyByUsername]  
(      
  @AMRSNTID varchar(100) = null  
)    
RETURNS TABLE    
AS    
RETURN    
(    
  WITH yourcte AS    
  (    
    SELECT EmployeeId, ManagerAMRSNTID, ManagerID, AMRSNTID, FullName, 0 as depth--, Name    
    FROM Employees    
    WHERE (AMRSNTID = @AMRSNTID) or (@AMRSNTID is null and managerID is null)
    UNION ALL    
    SELECT e.EmployeeId, e.ManagerAMRSNTID, e.ManagerID, e.AMRSNTID, e.FullName, y.depth+1 as depth--, e.Name    
    FROM Employees e    
    JOIN yourcte y ON e.ManagerAMRSNTID = y.AMRSNTID
  )    

SELECT EmployeeId, ManagerID, AMRSNTID, FullName, depth--, Name    
FROM yourcte    
)