我需要在SQL Developer中创建一个可以将数据从一列移动到另一列的过程。这些列位于不同的表中,因此我不知道如何编写代码。
我想使用Cursor从一列传输数据然后使用语句的当前插入到其他列,虽然我不知道如何做并可以使用一些帮助。 我甚至不知道你怎么能这样做。 表1是使用customernumber,first namn,last namne和password构建的 表2只是customernumber和密码。 我需要将密码从表2转移到表1
Cursor c_newpass is
select */passwd/cnumbr/cnmbr,passwd -- dont know what to select here --
from customersecurity
for update of --passwd, which is in a column in another table called customer--
我在这里打字^ ^然后呢?
在此之后你开始这个程序,我不知道下一步要写什么,一些关于
update passwd
from customer
where current of c_newpass
我真的不知道,但我知道我写的例子不起作用。但我想一个循环可以用来更新每一行,因为我假设你不能同时更新整个列。 如果有人可以编写整个程序,我会很感激,至少是一个例子,所以我知道该怎么做。 感谢您提供各种帮助!
答案 0 :(得分:1)
<强>更新强> 由于您使用的是Oracle,因此 link 上接受的答案可能有助于为您解决问题......
创建光标时,您将在两个表之间加入,并指定要更新的更新(要更新的列)。从那里,WHERE CURRENT OF c_newpass
仅引用与c_newpass关联的FETCH语句处理的最新行。
这只是我认为它如何运作的粗略概念。
Cursor c_newpass IS
select customersecurity.password, customersecurity.cnumbr, table1.cnumbr, table1.password
from customersecurity, table1
for update of table1.password
然后你应该能够遍历c_newpass,获取下一行并更新table1
Update table1
Set password = password
WHERE CURRENT OF c_newpass
SQL SERVER示例:
它可能不是您需要的,但它可以向您展示游标如何工作以及它们如何实现您的需求。我有2个表,我需要将Foo中的名称传输/复制到Bar中的名称,因为Bar表的名称开头为NULL。我创建了2个变量,一个用于ID,一个用于名称,用于保存光标(someCursor)当前所在的内容。设置光标后,您需要从中获取FETCH NEXT
语句中的项目,并使用INTO
设置@ID
和@Name
的变量。我通过检查@@Fetch_Status
来启动while循环,以确保前一个语句成功。如果是这样,我使用刚刚设置的变量来更新Bar表,匹配ID并使用@Name的内容更新Name列。完成后,我再次使用FETCH NEXT
获取光标中的下一个项目。假设光标中有另一个项目,并且它成功了,它将重新执行此操作。
我认为您使用的是与SQL Server不同的DBMS,但概念应该类似。您将根据customersecurity表创建游标,选择ID和密码,然后根据这些列更新新表。
Create Table Foo(
ID int identity primary key,
Name varchar(20)
)
Create Table Bar(
ID int identity primary key,
Name varchar(20)
)
Insert Into Foo Values('ABC')
Insert Into Foo Values('XYZ')
Insert Into Foo Values('JMK')
Insert Into Bar Values(NULL)
Insert Into Bar Values(NULL)
Insert Into Bar Values(NULL)
declare @ID int, @name varchar(20)
Declare someCursor CURSOR FOR
Select ID, Name From Foo order by ID
OPEN someCursor
FETCH NEXT FROM someCursor
INTO @ID, @name
WHILE @@Fetch_Status = 0
BEGIN
Update Bar
Set Name = @Name
Where ID = @ID
FETCH NEXT FROM someCursor
INTO @ID, @name
END
Close someCursor
Deallocate someCursor
select * from Foo
select * from Bar