DECLARE topScorer INT default 0;
SELECT id INTO topScorer FROM game_player
WHERE game_player.score = (SELECT max(score) FROM game_player)
一个不好的例子,但很容易由幼稚的编码产生......如果返回多行,它在我的测试中不起作用,我怎样才能将第一个返回的行放入变量中?
DECLARE topScorer INT default 0;
SELECT id INTO topScorer FROM game_player
WHERE game_player.score = (SELECT max(score) FROM game_player)
一个不好的例子,但很容易由幼稚的编码产生......如果返回多行,它在我的测试中不起作用,我怎样才能将第一个返回的行放入变量中?
你只需要一个分数吗?
SELECT id
INTO topScorer
FROM game_player
WHERE game_player.score = ( SELECT max(score) as maxScore
FROM game_player
) LIMIT 1
更新:Rufo 爵士是对的,上面的代码现已更正。
在子查询中应用限制以仅从子查询中获取 1 个值
SELECT id
INTO topScorer
FROM game_player
WHERE game_player.score = ( SELECT max(score)
FROM game_player LIMIT 1 );
或者从下面使用的子查询中获取多个值:
SELECT id
INTO topScorer
FROM game_player
WHERE game_player.score in ( SELECT max(score)
FROM game_player );
1)在SP中声明变量:
declare @CourseID int
set @CourseID = 0
2)我们首先需要两个查询来为变量分配 ID,而内部查询则只选择前 1 个记录表单表。在第一个查询的 where 子句中,我们将 ID 与内部查询的结果进行比较:
SELECT @CourseID = ID FROM Course ID = ( Select Top 1 ID from Course )
3)现在检查变量值:
if(@CourseID > 0 )
Begin
//This mean ID of first row is assigned to CourseID
End
Else
Begin
//Can't found any record.
End