您的位置:首页 > 数据库 > Oracle

论MySQL中如何代替Oracle中select into new_table from old_table

2013-12-15 18:04 561 查看
v_receipt warehouse_receipt%ROWTYPE;-- 这里创建表类型,v_receipt复刻了warehouse_receipt的类型(相当于拥有了所有相同的字段)

select * into v_receipt_detail from warehouse_receipt_detail d where d.receipt_detail_id = v_detailId;

**而在MySQL总无法用select into new_table from old_table这个语句**

但是MySQL中有temporary table这个临时表

如何复刻另一张表呢,语句来了

create temporary table new_table (select * from old_table)

这样就创建了一个新的临时表

drop table if exists temp_table;
create temporary table temp_table(select * from test_table);
select name from temp_table where id=2; -- 这句话同样能用

那么,为什么要用这种表变量和复刻的临时表呢?

其实这种临时表是动态的,在满足某种筛选条件下,产生的筛选出的主表

test_table



delimiter $$
-- drop table if exists temp_table;
create procedure temp_test()
begin
drop table if exists temp_table;
create temporary table temp_table(select * from test_table);
-- set @name=temp_table.name;
select name from temp_table where id=2;
end$$
delimiter


测试

call temp_test()

结果

name

------

nyu-ploy

另保留一段代码

delimiter $$
drop procedure if exists test_at $$
create definer=root@localhost procedure test_at()
begin
declare i1 integer default 1;
set i1=i1+1;
set @i2=i2+1;
select i1,@i2;
end $$
delimiter;


**但重点是在oracle 中,表类型可以直接引用字段,即

v_inventoryTotal warehouse_inventory_total%ROWTYPE

v_inventoryTotal.XXId可以直接用,特别是ROWTYPE的表只有一行时,此时引用字段就是一个值

但是对于临时表 temp_table不可以直接 '.id'同时实质表也不可以

在MySQL中引用字段都要起别名 ,这和对象的道理一样,所以想用其中的字段,只能这样

delimiter $$
drop procedure if exists temp_test $$
create definer=root@localhost procedure temp_test()
begin
declare i1 integer default 1;
drop table if exists temp_table;
create temporary table temp_table(select * from test_table t where t.id=2);
select name into @temp_table_name from temp_table;
select @temp_table_name;
end $$
delimiter;


call temp_test ,就有一个值出来 即nyu-poly

如果这里where t.id>2,就会报错:Result consisted of more than one row 即@temp_table_name不可以是多个值
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐