Sql 查询中的多个IFs
我正在尝试编写以下SQL查询,其中我必须为不同的输入选择不同的函数。函数在检查@Dept参数后返回每个部门的员工人数Sql 查询中的多个IFs,sql,sql-server,tsql,Sql,Sql Server,Tsql,我正在尝试编写以下SQL查询,其中我必须为不同的输入选择不同的函数。函数在检查@Dept参数后返回每个部门的员工人数 DECLARE @Dept varchar(10)='IT' IF @Dept='IT' Select count(Employees) from dbo.ITDept() IF @Dept='HR' Select count(Employees) from dbo.HRDept() IF @Dept='Accounts' Select count(Em
DECLARE @Dept varchar(10)='IT'
IF @Dept='IT'
Select count(Employees) from dbo.ITDept()
IF @Dept='HR'
Select count(Employees) from dbo.HRDept()
IF @Dept='Accounts'
Select count(Employees) from dbo.AccountsDept()
是否有更好的方法编写此查询?如果无法访问表函数的基本对象,答案是“否”。
它可以写在一个查询中,但没有附加值 我想你应该试着像在查询中使用字段一样使用它。你可以用这个来处理
Declare @dept varchar(10)
SELECT CASE WHEN @dept='IT' THEN
(Select
count(Employees) from dbo.ITDept())
WHEN @dept='IT' THEN (Select count(Employees) from dbo.HRDept())
WHEN @dept='IT' THEN (Select count(Employees) from dbo.AccountsDept())
ELSE (Select count(Employees) from dbo.ITDept())
END
是,用户案例而不是IF(因为在您的示例中,无论
@Dept
的值是多少,都有三个评估)。您有权访问这些表函数的基表吗?没有。我只能使用这些函数访问表。