fre*_*and 7 sql-server subquery query-variables
是否可以在查询中设置/读取变量?
伪代码:
SELECT animal_name,
@tallest_animal = (select top 1 height from animal order by height desc) as tallest,
@smallest_animal = (select top 1 height from animal order by height asc) as smallest
FROM animals
WHERE height BETWEEN @smallest_animal AND @tallest_animal
Run Code Online (Sandbox Code Playgroud)
我知道结果可以通过使查询不同来实现,我的问题的实际用法很难解释.
它是有问题的Microsoft SQL Server.:)
是的,您可以在查询中设置变量.你的语法实际上非常接近.
为此,您需要:
SELECT @YourVariable = Column
FROM Animals
Run Code Online (Sandbox Code Playgroud)
注意:在为变量分配字段时,不能使用AS.
您必须确保将查询中的所有字段分配给变量,否则您将收到以下错误:
为变量赋值的SELECT语句不能与数据检索操作结合使用.
要解决此问题,只需将AnimalName分配给@AnimalName变量即可.
编辑:
DECLARE @AnimalName VARCHAR(20)
DECLARE @TallestAnimal INT
DECLARE @SmallestAnimal INT
SELECT @AnimalName = animal_name,
@TallestAnimal = (select top 1 height from animal order by height desc),
@SmallestAnimal = (select top 1 height from animal order by height asc)
FROM animals
WHERE height BETWEEN @SmallestAnimal AND @TallestAnimal
Run Code Online (Sandbox Code Playgroud)
此代码假设高度字段的类型为INT.
不,不可能,而是这样使用:
DECLARE @tallest_animal int, @smallest_animal int
SET @tallest_animal=(SELECT max(height) from animals)
SET @smallest_animal=(SELECT min(height) from animals)
SELECT animal_name from animals where height between @tallest_animal AND @smallest_animal
Run Code Online (Sandbox Code Playgroud)
这样的事情会起作用,但是我不确定您在寻找什么。
您可以使用派生表而不是变量.
select A.animal_name, M.tallest, M.smallest
from animals A
inner join
(
select max(height) as tallest,
min(height) as smallest
from animal
) M
on A.height between M.smallest and M.tallest
Run Code Online (Sandbox Code Playgroud)