表变量和SQL Server中的空值检查

时间:2012-08-22 15:29:24

标签: sql sql-server

我有以下查询。

CREATE TYPE [dbo].[DeptIdList] AS TABLE(
    [DepartmentId] [smallint] NULL
)
GO
set nocount on

declare @department_ids DeptIdList
declare @tableContainsRecords int = 0

insert into @department_ids
values
(5), (6), (7), (8), (9)

select d.DepartmentID, d.Name, d.GroupName
  from HumanResources.Department as d
  right outer join @department_ids as di on
    d.DepartmentID = di.DepartmentID

如果@department_ids包含行,我想选择特定部门;如果不是,SELECT应该返回部门表中的所有记录。

最简单和最佳的方法是什么?

1 个答案:

答案 0 :(得分:1)

这应该有效:

SELECT d.DepartmentID, d.Name, d.GroupName
FROM HumanResources.Department d
WHERE DepartmentID IN (SELECT DepartmentID FROM @department_ids)
OR (SELECT COUNT(*) FROM @department_ids) = 0