我在下面尝试:
--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;
与前两个(声明和插入)查询一起执行。
答案 0 :(得分:2)
不要使用表格,使用变量:
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');
答案 1 :(得分:0)
如果没有tablename
alias
子句,则不能将where
用作selecting
。你必须从表中选择。试试这个。
select * from employee
where employee.salary > (select salary from @tempemp)