1
DECLARE topScorer INT default 0;

SELECT id INTO topScorer FROM game_player
WHERE game_player.score = (SELECT max(score) FROM game_player)

A bad example but one that could easily result from naive coding... it doesn't work in my testing if multiple rows are returned, how can I get the first returned row into the variable?

4

4 に答える 4

2

Do you need just the one score?

SELECT id 
  INTO topScorer 
  FROM game_player
 WHERE game_player.score = (   SELECT max(score) as maxScore 
                                 FROM game_player 
                                 ) LIMIT 1

Update: Sir Rufo was right, the code above has now been corrected.

于 2013-01-15T10:57:46.840 に答える
1

Use LIMIT x to ensure you are receiving only x rows from your query.

In this case you only want to get 1 row:

SELECT id 
  INTO topScorer 
  FROM game_player
 WHERE game_player.score = ( SELECT max(score) 
                               FROM game_player )
 LIMIT 1

SQL Fiddle DEMO

As a working alternative you can also use this

  SELECT id 
    INTO topScorer 
    FROM game_player
ORDER BY score DESC
   LIMIT 1

SQL Fiddle DEMO

于 2013-01-15T12:59:36.253 に答える
1

Apply limit in sub query to get only 1 value from sub query

SELECT id 
  INTO topScorer 
  FROM game_player
 WHERE game_player.score = ( SELECT max(score) 
                               FROM game_player  LIMIT 1 );

Or to get multiple value from sub query used below one:

SELECT id 
  INTO topScorer 
  FROM game_player
 WHERE game_player.score in ( SELECT max(score) 
                               FROM game_player );
于 2013-01-15T13:39:59.050 に答える
0

1) declare variable in SP:

declare @CourseID int 
set @CourseID = 0

2) We need two query first for assign ID to variable and inner query for select only Top 1 record form table. In where clause of first query we compare ID with result of inner query:

SELECT @CourseID = ID FROM Course ID = ( Select Top 1 ID from Course ) 

3) Now check Variable value:

 if(@CourseID > 0 )
    Begin
           //This mean ID of first row is assigned to CourseID
    End
    Else 
    Begin
      //Can't found any record.
    End
于 2018-09-28T06:03:58.040 に答える