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');
...
Related
I am new to Oracle and learning; I am simply trying to run this T-SQL query
DECLARE #SearchObj varchar(100);
SET #SearchObj='%aldbrough%';
SELECT
obj_id,
name,
description
FROM
agnis.t_object
WHERE
lower(name) = ObjToSearch ;
I am using SQL Developer Oracle tool which also have a "Scratch Editor" to help with translation from T-SQL. When i run the tool it gave me this code
DECLARE
v_SearchObj VARCHAR2(100);
BEGIN
v_SearchObj := '%aldbrough%' ;
SELECT obj_id ,
NAME ,
DESCRIPTION
FROM agnis.t_object
WHERE LOWER(NAME) = ObjToSearch;
END;
but the same tool give me this error
Error report -
ORA-06550: line 10, column 26:
PL/SQL: ORA-00904: "OBJTOSEARCH": invalid identifier
ORA-06550: line 6, column 4:
PL/SQL: SQL Statement ignored
06550. 00000 - "line %s, column %s:\n%s"
*Cause: Usually a PL/SQL compilation error.
so what is the correct syntax to use a variable into a LIKE clause that returns multiple rows?
I hope I do not have to use cursors etc for such of a simple statement as suggested in this question
Well, yes - those "translators" don't always do what they are supposed to.
This is how your code should look like:
use like, not = in the where clause
in PL/SQL, you have to put the result of the select statement into something - for example, locally declared variables (as my example shows).
So:
DECLARE
v_SearchObj VARCHAR2 (100) := '%aldbrough%';
--
v_obj_id t_object.obj_id%TYPE;
v_name t_object.name%TYPE;
v_description t_object.description%TYPE;
BEGIN
SELECT obj_id, NAME, DESCRIPTION
INTO v_obj_id, v_name, v_description
FROM agnis.t_object
WHERE LOWER (NAME) LIKE v_searchobj;
END;
If such a code returns an error - too_many_rows (and yes, it does), then one option is to loop through rows and do something (such as display those values):
DECLARE
v_SearchObj VARCHAR2 (100) := '%aldbrough%';
BEGIN
FOR cur_r IN (SELECT obj_id, NAME, DESCRIPTION
FROM agnis.t_object
WHERE LOWER (NAME) LIKE v_searchobj)
LOOP
DBMS_OUTPUT.put_line (
'Name = ' || cur_r.name || ', description = ' || cur_r.description);
END LOOP;
END;
Since this is tagged SQL Developer, use a bind variable:
SELECT obj_id,
name,
description
FROM agnis.t_object
WHERE lower(name) = :ObjToSearch;
and SQL developer will pop up a dialog box where you can set the value of the ObjToSearch variable.
If you want to specify the bind variable in code then:
VARIABLE objtosearch VARCHAR2(50)
BEGIN
:objtosearch := '%aldbrough%';
END;
/
SELECT obj_id,
name,
description
FROM agnis.t_object
WHERE lower(name) = :ObjToSearch;
And run the statements as a script using F5 rather than as individual statements.
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;
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;
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.
Despite having spent an hour researching I can't seem to figure out how to correctly define a variable and then use it in your SQL.
This is what I have so far produced:
DECLARE startDate DATE := to_date('03/11/2011', 'dd/mm/yyyy');
of which I get the reply:
ORA-06550: line 1, column 63: PLS-00103: Encountered the symbol
"end-of-file" when expecting one of the following:
begin function package pragma procedure subtype type use form current
cursor
Details: DECLARE startDate DATE := to_date('03/11/2011',
'dd/mm/yyyy'); Error at line 1 ORA-06550: line 1, column 63:
PLS-00103: Encountered the symbol "end-of-file" when expecting one of
the following:
begin function package pragma procedure subtype type use form current
cursor
I'd love to find out how to do such a simple task!
Your variable declaration is correct.
The DECLARE keyword is used to define variables scoped in a PL/SQL block (whose body is delimited by BEGIN and END;). How do you want to use this variable?
The following PL/SQL works fine for me:
DECLARE
startDate DATE := to_date('03/11/2011', 'dd/mm/yyyy');
reccount INTEGER;
BEGIN
SELECT count(*) INTO reccount
FROM my_table tab
WHERE tab.somedate < startDate;
dbms_output.put_line(reccount);
END;
You can also use the DEFINE statement to use simple string substitution variables. They are suitable for a client like SQL/PLUS or TOAD.
DEFINE start_date = "to_date('03/11/2011', 'dd/mm/yyyy')"
SELECT COUNT(*) from my_table tab where tab.some_date < &start_date;
To accomplish what you're attempting in Toad, you don't need to declare the variable at all. Simply include your variable prefaced with a colon and Toad will prompt you for the variable's value when you execute the query. For example:
select * from all_tables where owner = :this_is_a_variable;
If this doesn't work initially, right-click anywhere in the editor and make sure "Prompt for Substitution Variables" is checked.
If you really want to do it similarly to the way SQL Server handles variables (or you want to be able to do the same thing in SQL*Plus), you can write it as follows:
var this_is_a_variable varchar2(30);
exec :this_is_a_variable := 'YOUR_SCHEMA_NAME';
print this_is_a_variable;
select * from all_tables where owner = :this_is_a_variable;
However, to make this work in Toad, you'll need to run it through "Execute as script", rather than the typical "Execute statement" command.
Take in mind that Oracle's PL/SQL is not SQL.
PL/SQL is a procedural language. SQL is not procedural, but you can define "variables" the user can enter via the "&var" syntax (see http://www.orafaq.com/node/515).
This is an old post, but in case anyone stumbles on this (as I just did), you can handle this with a CTE:
with params as (
select date '2011-11-03' as startdate
from dual
)
select . . .
from params cross join
. . .
Almost the same syntax works in SQL Server (minus the date-specific stuff and from dual).
Solution
DEF startDate = to_date('03/11/2011', 'dd/mm/yyyy');
Select &startDate from dual;