SQL:变量声明

时间:2017-02-20 16:37:20

标签: oracle select declare

在sql中定义变量的最佳实践是什么?我在这里和其他地方看过其他一些帖子,但是我已经尝试过的任何帖子都没有用过。

我使用的是以下语法,但马不喜欢干草。

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;

这给我一些错误,从“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.

就目前的应用而言,我刚刚开始时只有非常少的数据库知识。我正在努力学习语法和使用。

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:1)

带有变量声明的PL / SQL块应该类似于:

declare
    var  number;
    var2 number;
begin
    select count(1)
    into var
    from dual;
    var2 := var * 2;
    dbms_output.put_line('Var2 = ' || var2);
end;

在SQLPlus中,您可以使用bind variables

variable var number
select count(1) into :var from dual;
select * from dual where rownum = :var;

甚至substitution variables

column var new_value valueFor_var
select count(1) as valueFor_var from dual;
select * from dual where rownum = &var;