是否可以在查询中设置/读取变量?
伪代码:
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
我知道可以通过改变查询来实现结果,我的问题的真正用途很难解释。
有问题的是 Microsoft SQL Server。 :)
最佳答案
是的,您可以在查询中设置变量。您的语法实际上非常接近。
为此,您需要:
SELECT @YourVariable = Column
FROM Animals
注意:将字段分配给变量时不能使用 AS。
您必须确保查询中的所有字段都分配给一个变量,否则您将收到以下错误:
A SELECT statement that assigns a value to a variable must not be combined with data- retrieval operations.
要解决这个问题,只需将 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
此代码假设高度字段的类型为 INT。
关于sql - 使用变量查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10206325/