在INSERT插入语句中引入条件限制选项实现数据插入控制 _MySQL, Oracle及数据库讨论区_Weblogic技术|Tuxedo技术|中间件技术|Oracle论坛|JAVA论坛|Linux/Unix技术|hadoop论坛_联动北方技术论坛  
网站首页 | 关于我们 | 服务中心 | 经验交流 | 公司荣誉 | 成功案例 | 合作伙伴 | 联系我们 |
联动北方-国内领先的云技术服务提供商
»  游客             当前位置:  论坛首页 »  自由讨论区 »  MySQL, Oracle及数据库讨论区 »
总帖数
2
每页帖数
101/1页1
返回列表
0
发起投票  发起投票 发新帖子
查看: 1737 | 回复: 1   主题: 在INSERT插入语句中引入条件限制选项实现数据插入控制         下一篇 
xiaojiang
注册用户
等级:少尉
经验:345
发帖:77
精华:0
注册:2011-8-31
状态:离线
发送短消息息给xiaojiang 加好友    发送短消息息给xiaojiang 发消息
发表于: IP:您无权察看 2015-6-17 16:58:25 | [全部帖] [楼主帖] 楼主

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表中。

--转自 北京联动北方科技有限公司




赞(0)    操作        顶端 
superstar
注册用户
等级:上尉
经验:525
发帖:2
精华:0
注册:2015-6-3
状态:离线
发送短消息息给superstar 加好友    发送短消息息给superstar 发消息
发表于: IP:您无权察看 2015-6-18 9:19:35 | [全部帖] [楼主帖] 2  楼

into 后面还能接 select * from t where y in (3000,4000),这个倒是没想到呢



赞(0)    操作        顶端 
总帖数
2
每页帖数
101/1页1
返回列表
发新帖子
请输入验证码: 点击刷新验证码
您需要登录后才可以回帖 登录 | 注册
技术讨论