Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use a declared variable in a SELECT statement

I'm using Oracle 10g and need to use a variable in a where clause of a SELECT; eg.

DECLARE
v_blah NUMBER;
BEGIN

v_blah := 13;

SELECT * FROM PEOPLE p WHERE p.LuckyNumber = v_blah;

END;

but am getting an error saying

PLS-00428: an INTO clause is expected in this SELECT statement

It seems to work fine in a DELETE or INSERT statement, so I'm not sure why it wouldn't work here.

like image 223
Jacob Avatar asked Jul 28 '11 14:07

Jacob


People also ask

How do you use variables in a select statement?

The syntax for assigning a value to a SQL variable within a SELECT query is @ var_name := value , where var_name is the variable name and value is a value that you're retrieving. The variable may be used in subsequent queries wherever an expression is allowed, such as in a WHERE clause or in an INSERT statement.

Can I use variable in select statement SQL?

Setting a Value in a Transact-SQL VariableA variable can also have a value assigned by being referenced in the select list of a SELECT statement.

Can we DECLARE variable in select query?

Variables in SQL procedures are defined by using the DECLARE statement. Values can be assigned to variables using the SET statement or the SELECT INTO statement or as a default value when the variable is declared. Literals, expressions, the result of a query, and special register values can be assigned to variables.

How do you select a variable in SQL?

SELECT @local_variable is typically used to return a single value into the variable. However, when expression is the name of a column, it can return multiple values. If the SELECT statement returns more than one value, the variable is assigned the last value that is returned.


2 Answers

The correct syntax is:

DECLARE
  v_blah NUMBER := 13;
  v_people_rec PEOPLE%ROWTYPE;
BEGIN
  SELECT * INTO v_people_rec FROM PEOPLE p WHERE p.LuckyNumber = v_blah;
END;

The select statement in PL/SQL requires a place where store the query result. In this example the place is v_people_rec variable.

The example above expects exactly one row to be returned. In other cases it will throw exceptions NO_DATA_FOUND or TOO_MANY_ROWS.

like image 75
user272735 Avatar answered Oct 13 '22 21:10

user272735


That isn't anything to do with your parameter, it is because you're executing your code as a procedural block of code so it doesn't allow you to select to nothing.

What do you want to do with the result of the query? Display it to the screen? If so, select it to a cursor, iterate through and use dbms_output.

like image 43
DoctorMick Avatar answered Oct 13 '22 22:10

DoctorMick