accessing a bind variable in sqlplus - sql

In the following example,
variable recordId number;
BEGIN
SELECT MAX(recordvalue)
INTO recordId
FROM sometable;
END;
PRINT recordid;
SELECT *
FROM someothertable
WHERE recordkey = &recordId;
The select statement on the last line cannot access the value of recordId.
I know i can access recordId inside the pl/sql block using :recordId but is there a way to access recordId in a sql statement that is not in a pl/sql block? (like in the last line).

You can use bind variables in SQL*Plus too, still as :recordId. The & version will prompt for a value, and has no direct relationship to the variable version.
variable recordId number;
BEGIN
SELECT MAX(recordvalue)
INTO :recordId
FROM sometable;
END;
/
PRINT recordid;
SELECT *
FROM someothertable
WHERE recordkey = :recordId;
The slightly more common way to assign values to bind variables is with exec :recordId := value;, but exec is really just shorthand for an anonymous block anyway.
Not sure why you'd want to mix and match like this though. If the intention is to use the result of one query in a later one, you could try new_value instead:
column x_val new_value y_val; -- could also noprint if you do not need to see the intermediate value
SELECT MAX(recordvalue) x_val
FROM sometable;
SELECT *
FROM someothertable
WHERE recordkey = &y_val;

Related

Oracle SQL: Declaring a variable and using the variable in other queries

I'm new to Oracle Database and I'm having some trouble with declaring variables and using that in other queries. For example, I want to create a variable called caseID with which store a number based on the select statement. Then I want to use that caseID in other queries I want to create. This is what I have:
DECLARE
caseID NUMBER;
BEGIN
SELECT case_id FROM cases WHERE user_id = 'test';
END;
SELECT * FROM version where case_id = :caseID
MINUS
SELECT * FROM version where version_type = 'A'
I'm not able to use the caseID in the version query, a popup comes for me to enter what caseID is.
With SQLPlus you can try to declare a SQLPlus variable (this should also work with any GUI tool that is compatible with this kind of variable declaration such as SQL Developer, TOAD, ...):
variable caseID number;
BEGIN
SELECT case_id INTO :caseID FROM cases WHERE user_id = 'test';
END;
/
select * from version where case_id = :caseID;
Another possibility that does not use special client syntax but only PL/SQL:
DECLARE
caseID number;
v version%ROWTYPE;
BEGIN
SELECT case_id INTO caseID FROM cases WHERE user_id = 'test';
SELECT * INTO v FROM version WHERE case_id = caseID;
END;
/
But in this case you have to code everything in PL/SQL and make sure to process output of SELECT statements.
I think what you are looking for is #set command in DBeaver to define and assign it at once and use it in the session:
#set userId='test'
#set caseId=(SELECT case_id FROM cases WHERE user_id = :userId)
SELECT * FROM version where case_id = :caseId

Declaring variables and select statement in a procedure

I'm writing a SQL procedure which should use calculated date stored as a local variable in a select statement. I'm using Oracle SQL developer. My code is:
create or replace PROCEDURE
my_procedure
AS
BEGIN
DECLARE
l_max_dt DATE;
BEGIN
SELECT MAX(TRX_DT)
INTO l_max_dt
FROM TABLE
WHERE 1=1;
end;
select * from TABLE where trx_dt = l_max_dt;
end;
This code gives me an error : " Error(14,48): PL/SQL: ORA-00904: "L_MAX_DT": invalid identifier" when select statement is present.
How can I store variables to use them in statements?
This is how you write a Procedure. Syntax is incorrect. Read about syntax Here
CREATE OR REPLACE PROCEDURE my_procedure
AS
l_max_dt DATE;
v_var TABLE2%ROWTYPE;
BEGIN
SELECT MAX (TRX_DT)
INTO l_max_dt
FROM TABLE1
WHERE 1 = 1;
-- Assuming the query will retrun only 1 row.
SELECT *
INTO v_var
FROM TABLE2
WHERE trx_dt = l_max_dt;
END;
Your issue is one of scope. In your procedure, you have a nested block, in which you declare the l_max_dt variable. Once the code has exited that block, the l_max_dt variable is no longer in scope - i.e. the outer block does not know anything about it.
There is no need to have a nested block in this instance - you can do it all in the same block, like so:
create or replace PROCEDURE my_procedure
AS
l_max_dt DATE;
BEGIN
SELECT MAX(TRX_DT)
INTO l_max_dt
FROM TABLE
WHERE 1=1;
-- commented out as this isn't valid syntax; there is a missing INTO clause
-- select *
-- from TABLE where trx_dt = l_max_dt;
END my_procedure;
However, you could simply do the query in one fell swoop - e.g.:
select *
from your_table
where trx_dt = (select max(trx_dt) from your_table);
A couple of points about your procedure:
In PL/SQL, if you use an implicit cursor (i.e. when you put a select statement directly in the body of the code) you need to have something to put the results into. You could bulk collect the results into an array, or you could ensure that you will receive exactly one row (or code error handling for NO_DATA_FOUND and TOO_MANY_ROWS) into a record or corresponding scalar variables.
You shouldn't use select * in your procedure - instead, you should explicitly state the columns being returned, because someone adding a column to that table could cause your procedure to error. There are exceptions to this "rule", but explicitly stating the columns is a good habit to get into.

Oracle SQL - SELECT with Variable arguments stored procedure

I'm struggling with a variable argument stored procedure that has to perform a SELECT on a table using every argument passed to it in its WHERE clause.
Basically I have N account numbers as parameter and I want to return a table with the result of selecting three fields for each account number.
This is what I've done so far:
function sp_get_minutes_expiration_default(retval IN OUT char, gc IN OUT GenericCursor,
p_account_num IN CLIENT_ACCOUNTS.ACCOUNT_NUM%TYPE) return number
is
r_cod integer := 0;
begin
open gc for select account_num, concept_def, minutes_expiration_def from CLIENT_ACCOUNTS
where p_account_num = account_num; -- MAYBE A FOR LOOP HERE?
return r_cod;
exception
-- EXCEPTION HANDLING
end sp_get_minutes_expiration_default;
My brute force solution would be to maybe loop over a list of account numbers, select and maybe do a UNION or append to the result table?
If you cast your input parameter as a table, then you can join it to CLIENT_ACCOUNTS
select account_num, concept_def, minutes_expiration_def
from CLIENT_ACCOUNTS ca, table(p_account_num) a
where a.account_num = ca.account_num
But I would recommend you select the output into another collection that is the output of the function (or procedure). I would urge you to not use reference cursors.
ADDENDUM 1
A more complete example follows:
create or replace type id_type_array as table of number;
/
declare
ti id_type_array := id_type_array();
n number;
begin
ti.extend();
ti(1) := 42;
select column_value into n from table(ti) where rownum = 1;
end;
/
In your code, you would need to use the framework's API to:
create an instance of the collection (of type id_type_array)
populate the collection with the list of numbers
Execute the anonymous PL/SQL block, binding in the collection
But you should immediately see that you don't have to put the query into an anonymous PL/SQL block to execute it (even though many experienced Oracle developers advocate it). You can execute the query just like any other query so long as you bind the correct parameter:
select account_num, concept_def, minutes_expiration_def
from CLIENT_ACCOUNTS ca, table(:p_account_num) a
where a.column_value = ca.account_num

How do you assign a sequence value to a variable?

I need to assign a sequence value to a variable for use later after the sequence value has been incremented. I've tried this but it gives an error:
variable imageID number;
select SEQ_IMAGE_ID.CURRVAL into :imageID from dual;
select * from IMAGES where IMAGE_ID = :imageID;
Error starting at line 2 in command:
select SEQ_IMAGE_ID.CURRVAL into :imageID from dual
Error report:
SQL Error: ORA-01006: bind variable does not exist
01006. 00000 - "bind variable does not exist"
I have triple checked that the sequence name is correct, any ideas?
You seem to be doing this in SQL*Plus or SQL Developer, from the variable declaration. You need to do the assignment in a PL/SQL block, either with an explicit begin/end or with the exec call that hides that:
variable imageID number;
exec select SEQ_IMAGE_ID.CURRVAL into :imageID from dual;
select * from IMAGES where IMAGE_ID = :imageID;
If you're using 11g you don't need to select, you can just assign:
variable imageID number;
exec :image_id := SEQ_IMAGE_ID.CURRVAL;
select * from IMAGES where IMAGE_ID = :imageID;
You could also use a substitution variable:
column tmp_imageid new_value image_id;
select SEQ_IMAGE_ID.CURRVAL as tmp_imageID from dual;
select * from IMAGES where IMAGE_ID = &imageID;
Note the change from : to indicate a bind variable, to & to indicate a substitution variable.
In PL/SQL, the variable needs to be declared, something like this:
declare
V_IMAGEID;
begin
select SEQ_IMAGE_ID.CURRVAL into V_IMAGEID from dual;
select * /*into ... */ from IMAGES where IMAGE_ID = V_IMAGEID;
end;
If you're using bind variables, the variable must be bound. The error message indicates this isn't the case. How exactly to bind variables depends on the language/situation. Make sure you use the right direction when binding variables. In the first (dual) query, you will need an out parameter. You may need to specify this.
just remove ':' before :imageId. If you are in a trigger use :new.imageid
the word variable should be removed as well
p.s. I mean anonymous block surely.

Oracle: select into variable being used in where clause

Can I change the value of a variable by using a select into with the variable's original value as part of the where clause in the select statement?
EI would the following code work as expected:
declare
v_id number;
v_table number; --set elsewhere in code to either 1 or 2
begin
select id into v_id from table_1 where name = 'John Smith';
if(v_table = 2) then
select id into v_id from table_2 where fk_id = v_id;
end if;
end;
Should work. Have you tried it? Any issues?
After parsing your select statements should have bind variables where your v_id is. The substitution is made when the statement is actually executed.
Edit:
Unless you're sticking constants into your queries, Oracle will always parse them into statements with bind variables - it enables the DBMS to reuse the same basic query with multiple values without reparsing the statement - a huge performance gain. The whole idea of a bind variable is runtime substitution of values into a parsed query. Think of it this way: in order to process a query, all of the values need to be known. You send them to the engine, Oracle does it's work, and returns a result. It's a serial process with no way for the output value to step on the input one.