2012-05-10 322 views
0

我已与SQL Server以前工作,并能学习如何创建临时变量,在SQL声明Oracle数据库临时变量

使用它们

我以前写的东西是这样的:

declare @Student nvarchar(255) 

select @Student = studentname from sometable where somecondition = 1 

declare @teacher nvarchar(255) 

select @teacher = teachername from sometable2 where somecondition >2 

然后

select @student, @teacher, other columns from sometable where some condition 

我想在ORACLE数据库中做同样的事情。

请帮忙!

+0

sqlplus具有使用“define”关键字和“&”作为替换的变量(请参阅http://docs.oracle.com/cd/B19306_01/server.102/b14357/ch5.htm#sthref1020) – tbone

回答

0

可以声明一个变量说

SOME_VAR VARCHAR2(255); 

然后在查询中使用它直接

SELECT DISTINCT YT.TEACHER_NAME 
    INTO SOME_VAR 
    FROM YOUR_TABLE YT 
WHERE YT.TEACHER_ID = 1; 

然后你可以自由地使用这个变量,SOME_VAR,进一步使用

中当然,这不会在一个简单的SQL语句中工作,但是如果您在程序块中使用它,就像一个过程。

希望它可以帮助

1

如果你想这样做,在SQL * Plus不使用PL/SQL,您可以使用substitution variables

column studentname new_value l_studentname 
select studentname from sometable where somecondition = 1; 

column teachername new_value l_teachername 
select teachername from sometable2 where somecondition >2; 

select '&l_studentname', '&l_teachername,' other columns 
from sometable where somecondition; 

new_value clausecolumn指令自动从指定的值任何后续选择到一个局部变量,我已经预先与l_,但你可以调用任何东西。然后,您在将来的查询中使用&变量替换语法引用该局部变量。

你可以在任何你通常有价值的地方使用它们。例如在where条款中。请注意,文本值必须用引号括起来,因此'&l_studentname';没有引号在这种情况下将被解释为一个列名,这是行不通的。