oracle中动态创建并执行sql命令
我正在学习数据库课程,在课程的实验部分开始时,我们通常必须删除之前创建的数据库中的所有表。我希望能够运行一个动态执行此操作的脚本,但似乎无法让它工作。这是我到目前为止的代码。
declare tname string(50);
cursor ctable is select table_name from user_tables;
begin
open ctable;
LOOP
FETCH ctable into tname;
if tname != '' then
execute immediate 'drop table ' || tname;
END if;
EXIT WHEN ctable%NOTFOUND;
END LOOP;
close ctable;
end;
如果有人能指出我做错了什么的正确方向,那就太好了。谢谢。
I am taking a database class and at the beginning of the lab section of the class we usually have to drop all the tables in the database created previously. I wanted to be able to run a script that does this dynamically, but cannot seem to get it to work. Here is the code I have so far.
declare tname string(50);
cursor ctable is select table_name from user_tables;
begin
open ctable;
LOOP
FETCH ctable into tname;
if tname != '' then
execute immediate 'drop table ' || tname;
END if;
EXIT WHEN ctable%NOTFOUND;
END LOOP;
close ctable;
end;
If someone could point me in the right direction as to what I am doing wrong that would great. Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Oracle 的
VARCHAR2
将空字符串视为NULL
。因此
相同
与返回
NULL
而不是TRUE
> 因为它没有定义。您可以通过
tname IS NOT NULL
检查NULL
。不过,
table_name
在user_tables
中是强制性的,因此不需要进行此检查。还有两件事:
%NOTFOUND
user_tables.table_name%TYPE
)的代码可能如下所示:
所以您 还可以使用隐式游标以获得更好的可读性:
Oracle's
VARCHAR2
treats empty strings asNULL
.So
is the same as
which will return
NULL
instead ofTRUE
since it is not defined.You can check for
NULL
bytname IS NOT NULL
.table_name
is mandatory inuser_tables
though, so there is no need for this check.Two more things:
%NOTFOUND
immediately after fetchinguser_tables.table_name%TYPE
)So your code could look like that:
You could also use an implicit cursor for better readability: