我有两个具有相同结构的 SQL
表。第一列是名为“opt”的唯一索引,第二列名为“val”。
在table1中填充默认值,例如:
opt val
path /tmp
file myfile.txt
day tuesday
time 11:00
第二个表 table2 将包含相同的行,但某些 val 列值可能会丢失,例如:
opt val
path /var/tmp
file
day
time 16:30
我想遍历 table2 中的每一行并询问“val 列中是否有值?”如果没有,则从 table1 获取 val 并更新 table2,因此表 2 最终将如下:
opt val
path /var/tmp
file myfile.txt
day tuesday
time 16:30
即填写表1中缺失的数据。
我正在寻找一种纯粹的SQL
方法来执行此操作(即不使用PHP
、ASP
等)。
我对 SQL
中的 IF/ELSE
语法有点熟悉,但我不确定如何迭代表中的每一行。有人能让我朝着正确的方向开始吗?
最佳答案
sql 游标
就是您正在寻找的东西。您可以查看一些在线教程以备将来需要,但这里有一个示例。
DECLARE
c_opt table2.opt%type; //variable to be used for selecting into
c_name table2.val%type; // variable to be used for selecting into
CURSOR c_table2 is // the actual cursor
SELECT opt,val FROM table2;
BEGIN
OPEN c_customers;
LOOP
FETCH c_table2 into c_opt, c_val ;
EXIT WHEN c_customers%notfound;
IF (c_val is null) THEN UPDATE table 2 set val = (Select val from table 1 where opt = c_opt);
END LOOP;
CLOSE c_customers;
END;
请告诉我们它是否有效,最诚挚的问候。
关于SQL将丢失的数据从一个表复制到另一个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31587707/