Sql &引用;必须声明标量变量";声明表的内部where子句

Sql &引用;必须声明标量变量";声明表的内部where子句,sql,sql-server,Sql,Sql Server,我在下面尝试: --create temporary table declare @tempemp TABLE( salary int ); --get maximum salary of employees in sbi insert into @tempemp select MAX(salary) as 'salary' from employee where company='sbi'; 现在我想知道所有收入超过sbi所有员工的姓名。我试过这个: select * from e

我在下面尝试:

--create temporary table
declare @tempemp TABLE(
  salary int
);

--get maximum salary of employees in sbi
insert into @tempemp
  select MAX(salary) as 'salary' from employee where company='sbi';
现在我想知道所有收入超过sbi所有员工的姓名。我试过这个:

select * from employee where employee.salary > @tempemp.salary;
但这给了我一个错误:

Must declare the scalar variable "@tempemp".
虽然这样做很好:

select * from @tempemp;

与前两个(declare和insert)查询一起执行时。

where
子句中,如果不选择
它,则不能将
tablename
用作
别名。您必须从表中进行选择。试试这个

select * from employee 
where employee.salary > (select salary from @tempemp)

不要使用表格,请使用变量:

declare @salary int;

select @salary = MAX(salary)
from employee
where company = 'sbi';

select *
from employee
where employee.salary > @salary;
如果确实使用表,则需要一个子选择:

select *
from employee
where employee.salary > (select salary from @tempemp.salary);
我认为您有理由单独存储该值,因为您可以:

select *
from employee
where employee.salary > (select max(salary) from employee where company = 'sbi');

您将其作为标量值与
employee.salary>@tempemp.salary
一起使用。
@tempemp
表中是否只有一行?它只有一列,因此您无法将其加入到
员工
,但在当前使用它的方式中,您需要
员工.salary>(从@tempemp…
中选择salary)。