ITPub博客

首页 > 数据库 > Oracle > 【INSERT】在INSERT插入语句中引入条件限制选项实现数据插入控制

【INSERT】在INSERT插入语句中引入条件限制选项实现数据插入控制

原创 Oracle 作者:OCMU联盟 时间:2011-09-05 23:36:23 0 删除 编辑
  Oracle的insert插入语句的功能很是强大,我们可以实现在插入的过程中仅允许插入指定的数据记录,功能展示在此,供参考。

1.环境准备
1)创建T表
sec@ora10g> create table t (x number, y number);

Table created.

2)初始化两条数据,用于后续插入语句比对
sec@ora10g> insert into t values (1,null);

1 row created.

sec@ora10g> insert into t values (2,2000);

1 row created.

sec@ora10g> select * from t;

         X          Y
---------- ----------
         1
         2       2000

2.尝试使用带限制条件的插入语句
1)以下两条SQL插入语句是符合条件的例子
这里我们使用的是“with check option”选项限制插入T表时Y列值只允许是3000或4000。
sec@ora10g> insert into (select * from t where y in (3000,4000) with check option) values(3,3000);

1 row created.

sec@ora10g> insert into (select * from t where y in (3000,4000) with check option) values(4,4000);

1 row created.

sec@ora10g> select * from t;

         X          Y
---------- ----------
         1
         2       2000
         3       3000
         4       4000

上面两条数据符合插入条件,插入成功。

2)尝试插入不符合条件的数据
sec@ora10g> insert into (select * from t where y in (3000,4000) with check option) values(5,5000);
insert into (select * from t where y in (3000,4000) with check option) values(5,5000)
*
ERROR at line 1:
ORA-01402: view WITH CHECK OPTION where-clause violation

sec@ora10g> select * from t;

         X          Y
---------- ----------
         1
         2       2000
         3       3000
         4       4000

显然,在这种约束条件下,我们是无法插入Y值不等于3000和4000的数据的。

3)去掉“with check option”选项再次尝试数据插入
sec@ora10g> insert into (select * from t where y in (3000,4000)) values(5,5000);

1 row created.

sec@ora10g> select * from t;

         X          Y
---------- ----------
         1
         2       2000
         3       3000
         4       4000
         5       5000

此时插入数据的约束已取消。数据可以成功插入到T表中。

3.小结
  本文给出了一种插入数据的特殊用法,目的是提醒大家,我们在使用常规插入技术的同时还有很多新奇的方法值得探索。

Good luck.

secooler
11.09.05

-- The End --

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/70034820/viewspace-2994253/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论
OCM联盟( Oracle Certified Master Union)是由侯圣文(ACE总监)发起的一个公益组织,旨在为每一个OCM大师提供一个可以继续展示自己才华,技术和实力的平台。

注册时间:2007-05-27

  • 博文量
    799
  • 访问量
    8406974