sql variable declaration - oracle

I am trying to declare a variable in workbench using an oracle db. I found two approaches which both don't seem to be recognized as workbench does not highlight either var nor define as command
define s = 'test'
SELECT &&s from dual
;
var s varchar(max)
exec: s := 'test'
SELECT &&s from dual
both throw an error 1064. You ahve an error in your sql syntax.
How can I declare a simple variable to do something like
x = 'test'
select * from t where y = x

You have two options.
When in PL/SQL, you have to declare it like this:
declare
l_s varchar2 := 'test';
begin
select l_s
into some_other_var
from dual
;
-- or
some_other_var := l_s;
end;
;
Or, when simply using in a query:
select :s
from dual
This will ask you for the value of s.

Related

Oracle PL/SQL - parameterizing SAMPLE clause in SELECT statement

I have a Oracle related question. I would like to select a random sample out of a view or table in such a way that the SAMPLE clause is parameterized.
Given the following table.
CREATE TABLE FOO AS
(SELECT LEVEL AS ID
FROM DUAL
CONNECT BY LEVEL < 101
);
The following construct works, using a literal parameter in the SAMPLE clause.
SELECT ID FROM FOO SAMPLE (15); -- this will get a 15% sample
However,
DECLARE
N NUMBER := 50;
BEGIN
FOR r IN
( SELECT ID FROM FOO SAMPLE (N) -- <<< this won't work
)
LOOP
DBMS_OUTPUT.PUT_LINE( r.ID );
END LOOP;
END;
This block blows up when we put a parameter in the SAMPLE clause. It compiles and works if we put it a literal.
But if it is a variable, I get the following:
ORA-06550: line 5, column 33:
PL/SQL: ORA-00933: SQL command not properly ended
Any ideas? I'm racking by brains where the syntax gets broken.
The syntax does not allow a variable there.
One workaround would be to construct the SELECT statement dynamically. For example:
declare
l_rc sys_refcursor;
n number := 5;
begin
-- replace "mtl_system_items" with your table...
open l_rc FOR 'select count(*) from mtl_system_items sample (' || n || ')';
-- replace call to RETURN_RESULT with whatever processing you want
DBMS_SQL.RETURN_RESULT(l_rc);
end;

SQL: Declaration of Variables

What is the best practice for defining variables in sql? I've seen some of the other posts here and other places, but nothing I've tried as of yet has worked.
I'm using the below syntax, but the horse doesn't like the hay.
declare #variablename number(10)
set #variablename = (select COLUMN_NAME from TABLE_NAME where ANOTHER_COLUMN_NAME='something')
select MORE_COLUMN_NAMES from "NAME" where ANOTHER_NAME=#variablename;
This gives me some errors starting at "declare."
Error report -
ORA-06550: line 1, column 9:
PLS-00103: Encountered the symbol "#" when expecting one of the following:
begin function pragma procedure subtype type "an identifier"
"a double-quoted delimited-identifier" current cursor delete
exists prior
The symbol "#" was ignored.
I'm just starting out with very little database knowledge in so far as the application of things. I'm trying to become more versed in syntax and use.
Any help would be appreciated.
A PL/SQL block with variable declaration should be something like:
declare
var number;
var2 number;
begin
select count(1)
into var
from dual;
var2 := var * 2;
dbms_output.put_line('Var2 = ' || var2);
end;
In SQLPlus you can use bind variables:
variable var number
select count(1) into :var from dual;
select * from dual where rownum = :var;
or even substitution variables:
column var new_value valueFor_var
select count(1) as valueFor_var from dual;
select * from dual where rownum = &var;

How to set Oracle bind variables when using SQLPlus?

How do I set Oracle bind variables when using SQLPlus?
Example:
SELECT orders.order_no FROM orders WHERE orders.order_date BETWEEN :v1 AND :v2
How do I set the dates of :v1 and :v2?
Notice the following:
VARIABLE is a SQLPlus command. You don't end it with a semicolon (;).
In the VARIABLE command, you do not precede the variable name with
colon (:).
Bind variable can't be of data type "date" - they are some sort of
character value.
For that reason, IN YOUR CODE you must use to_date() with the
proper format model, or some other mechanism, to convert string to
date. That is currently missing in your code. NEVER compare dates to
strings!
Brief demo below.
SQL> variable v1 varchar2(20)
SQL> exec :v1 := '2015/12/22';
PL/SQL procedure successfully completed.
SQL> select 1 as result from dual where to_date(:v1, 'yyyy/mm/dd') < sysdate;
RESULT
----------
1
In common
you may use define and use variable with &
define x = 12 ;
select &x from dual;
Or varable
variable x refcursor;
begin
open :x for select * from dual connect by level < 11;
end;
/
print x

Oracle declare variable syntax

Converting SQL to Oracle using “SQL Navigator” to test and running into syntax problems when declaring a variable. Have read other related posts but nothing seems to be working.
Goal is to set a variable “strDate” to the current date as a string in this format YYYYMMDD.
Code I've tried is:
declare
strDate := TO_CHAR(sysdate, 'YYYYMONDD');
BEGIN
SELECT ColumnA a, ColumnB b, ColumnC c
from table1, table2
where stringcolumn = strDate;
end;
Error result is:
"ORA-06550; line 2 column 10: ...encountered the symbol "=" when expecting...."
Also tried:
var strDate varchar2(8)
exec :strDate := TO_CHAR(sysdate, 'YYYYMONDD')
BEGIN
SELECT....;
end;
The query itself is a union query and I can run the individual 'parts' with hard coded values just fine. Just can't seem to get it to accept variables for some reason.
Proper syntax would be:
declare
DateFrom varchar2(20):= TO_CHAR(sysdate, 'YYYYMONDD');
...

What is the simplest way to define a local variable in Oracle?

In the SQL Server, I can define local variables like this.
declare #id number := 1000
select * from tbl_A where id = #id;
select * from tbl_B where id = #id;
It is very convenient.
I tried to do same thing in PL/SQL but it doesn't work.
DECLARE id number;
select 1000 into id from dual;
Do you know how to do something similar? The simplest method is my objective.
If you want to define a local variable in PL/SQL, you need a complete PL/SQL block
DECLARE
id NUMBER;
BEGIN
SELECT 1000
INTO id
FROM dual;
END;
or just
DECLARE
id NUMBER := 1000;
BEGIN
<<do something that uses the local variable>>
END;
If you want to declare a variable in SQL*Plus
SQL> variable id number
SQL> begin
select 1000 into :id from dual;
end;
/
SQL> print id
ID
----------
1000
SQL> SELECT * FROM tbl_a WHERE id = :id
An alternative to DECLARE Block is to use a WITH Clause:
WITH my_params AS (
SELECT 123 AS min_id FROM DUAL
)
SELECT *
FROM some_table
WHERE id > (SELECT min_id FROM my_params)
It is more portable as many vendors support the WITH clause and you can change seamless from parameter to dynamic value. For example:
WITH my_params AS (
SELECT min(id) AS min_id FROM some_id_table
)
SELECT *
FROM some_table
WHERE id > (SELECT min_id FROM my_params)
Solution for Oracle SQL
DEF x = foo
SELECT '&x' FROM dual;
The result will be : foo
NB: The variable will keep the value even after execution. To clear variable run UNDEFINE x.
General syntax to declare variable in PL/SQL is
var_nm datatype [NOT NULL := var_value ];
var_nn is the name of the variable.
datatype is a valid PL/SQL datatype.
NOT NULL is an optional specification on the variable which this variable cannot be assigned null value.
var_value or DEFAULT value is also an optional specification, where you can initialize a variable with some specific value.
Each variable declaration is a separate statement and must be terminated by a semicolon.
We can assign value to variables in one of the following two ways -
direct assignment (Eg. var_nm:= var_value;)
Using select from (Eg. SELECT col_nm INTO var_nm FROM tbl_nm [WHERE clause];)
In you case as Justin Cave has already mentioned it can be
DECLARE
id number;
BEGIN
SELECT 1000 into id from dual;
dbms_output.put_line('id : '|| id );
END;
/
OR
DECLARE
id number := 1000;
BEGIN
dbms_output.put_line('id : '|| id );
END;
/
NOTE: '/' i.e Back slash after END keyword indicates to execute the above PL/SQL Block.
(Just stumbled across this thread.) Beginning with SQL*Plus 12.2, you can declare and assign a value at the same time:
SQL> var id number = 1000
SQL> select * from tbl_A where id = :id;
Oracle calls it input binding.
If you must do it in PL/SQL, the answer was given by others.

Resources