2012-08-22 35 views
0

我有以下查詢。表變量和在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

這應該工作:

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