将数据从一个表移动到另一个类似表
我通常会尝试避免使用游标和循环遍历结果集,但是在以下场景中如何实现这一点而不循环遍历 SomeTable
并将行逐一插入到 MyTable
中?
简单的架构如下:
MyTable
- Name VARCHAR(20)
- Code1 CHAR(5)
- Code2 CHAR(5)
SomeTable
- Name VARCHAR(20)
- SomeCode1 CHAR(10)
- SomeCode2 CHAR(10)
SQL 语句:
INSERT INTO MyTable (Name, Code1, Code2)
SELECT Name, First Five Chars of SomeCode1 Only if SomeCode2 is not null or empty or doesn't have a certain value, SomeCode2
FROM SomeTable
我在 Java 代码中执行此操作,但我不确定是否可以在整个 INSERT INTO SELECT
语句中执行此操作。我几乎即将编写一个包含单个 INSERT 语句的 for 循环。我应该在数据库中创建某种函数还是......?我正在使用 DB2。
I usually try to avoid using cursors and looping through a result set but how can I accomplish this in the following scenario without looping through SomeTable
and inserting rows one by one to MyTable
?
Simple schema is as follows:
MyTable
- Name VARCHAR(20)
- Code1 CHAR(5)
- Code2 CHAR(5)
SomeTable
- Name VARCHAR(20)
- SomeCode1 CHAR(10)
- SomeCode2 CHAR(10)
SQL Statement:
INSERT INTO MyTable (Name, Code1, Code2)
SELECT Name, First Five Chars of SomeCode1 Only if SomeCode2 is not null or empty or doesn't have a certain value, SomeCode2
FROM SomeTable
I'm doing this inside Java code but I'm not sure if it's possible to do this in one whole INSERT INTO SELECT
statement. I'm almost close to writing a for loop with single INSERT
statements in them. Should I create some sort of a function in the database or.. ? I'm using DB2.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您希望在未找到条目时出现空条目:
- 或 -
如果您不希望在未找到条目时存在任何行:
If you want null entries when not found:
-or-
If you don't want any row to exist when entries aren't found: