Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/lua/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在SQL Server中查找表中的最大年龄时出错_Sql_Sql Server - Fatal编程技术网

在SQL Server中查找表中的最大年龄时出错

在SQL Server中查找表中的最大年龄时出错,sql,sql-server,Sql,Sql Server,我们可以简单地通过使用 SELECT TOP 1 age FROM Head1 ORDER BY Age DESC 但我已经尝试在SQLServer中使用while循环 代码 declare @a int, @m int, @maxo int; set @maxo = 0; while(@a<10) begin select name, @m = age from head1 where ID = @a; if @m>@maxo @maxo = @m;

我们可以简单地通过使用

SELECT TOP 1 age FROM Head1 ORDER BY Age DESC
但我已经尝试在SQLServer中使用while循环

代码

declare @a int, @m int, @maxo int;
set @maxo = 0;
while(@a<10)
begin
    select name, @m = age from head1 where ID = @a;
    if @m>@maxo
       @maxo = @m;
    set @a=@a+1;
end
print @maxo
声明@a int、@m int、@maxo int;
设置@maxo=0;
当(@a@maxo
@maxo=@m;
设置@a=@a+1;
结束
打印@maxo
错误

味精141,第15级,状态1,第5行
为变量赋值的SELECT语句不得与数据检索操作结合使用

味精102,第15级,状态1,第7行
“@maxo”附近的语法不正确


我有点被困在这里了。请帮助大家….

异常文本是不言自明的

由于您无法在分配
@m
的同一语句中检索
名称
(实际上您没有在任何地方使用此
名称
,因此看起来您不需要它),因此必须更改此行

select name, @m = age from head1 where ID = @a;

或者,如果您确实需要某个名称,则还应将其分配给某个变量,而不仅仅是选定的:

select @n = name, @m = age from head1 where ID = @a;
但一般来说,这不起作用,因为
head1
中可能有多条记录满足条件
ID=@a
。只有当查询只返回一行时,为变量赋值才起作用

注意-使用循环是查找最大值的非常低效的方法。

有两个问题:

第1期:

您得到的错误是不言自明的,即在为变量赋值时无法选择列

您可以这样解决它:

select @name = name, @m = age from head1 where ID = @a;
DECLARE @rows bigint
SET @rows = (SELECT COUNT(1) FROM head1)
第二期:

在这种情况下,我认为从表中查找最大年龄根本不需要该查询

SELECT Name, Age FROM Head1 WHERE Age = (SELECT MAX(Age) FROM Head1)

使用循环不仅效率低下,而且如果您的表很大,它还会造成性能瓶颈。

首先,我应该询问您有关
(@aRefer this:很高兴你发现所有的答案都很有用!但是你只能给一个被接受的分数。因为你最后选择的一个被接受的答案也是一个重复的帖子,所以我删除了那个,让你有机会选择一个对你帮助最大的帖子。:-)
declare @a int, @m int, @maxo int 
declare @name NVARCHAR(100)
set @maxo = 0;
while(@a<10)
begin
    select @name = name, @m = age from head1 where ID = @a;
     if @m>@maxo
       SET @maxo = @m;
       set @a=@a+1;
END
PRINT @name +  ',' + CAST(@maxo AS NVARCHAR(50))
SELECT Name, Age FROM Header1 WHERE Age = (SELECT MAX(Age) FROM Header1)
DECLARE @rows bigint
SET @rows = (SELECT COUNT(1) FROM head1)
DECLARE @max int
SET @max = 0

SELECT @max = CASE WHEN @max < age THEN age ELSE @max END
FROM head1
SET @m = (SELECT h1.age 
          FROM (SELECT *, ROW_NUMBER() OVER (ORDER BY head1.age) AS rn 
                FROM head1) h1 
          WHERE h1.rn = @a;
select name, @m = age from head1 where ID = @a;