将数据从一个表移动到另一个表

时间:2011-05-03 19:53:35

标签: java sql servlets db2

我通常会尝试避免使用游标并循环遍历结果集但是如何在以下方案中完成此操作而不循环遍历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语句中执行此操作。我几乎接近编写一个for循环,其中包含单个INSERT语句。我应该在数据库中创建某种函数还是..?我正在使用DB2。

3 个答案:

答案 0 :(得分:1)

INSERT INTO MyTable (Name, Code1, Code2)
SELECT Name, 
  CASE When coalesce(SomeCode2, '')='' Then NULL
       When SomeCode2=@somevalue Then NULL
       Else substring(SomeCode1, 1, 5)
, SomeCode2
FROM SomeTable

答案 1 :(得分:0)

insert into MyTable (Name, Code1, Code2)
select Name, case when (SomeCode2 is not null and length(trim(SomeCode2)) <> 0) then substr(SomeCode1, 0, 5) end, SomeCode2 from SomeTable;

答案 2 :(得分:0)

如果您未找到空条目:

insert into MyTable (Name, Code1, Code2)
select
  Name,
  if(not isnull(SomeCode2) and SomeCode2 != ''
     and SomeCode2 != 'foo', substring(SomeCode1,1,5), null),
  SomeCode2
  from SomeTable
;

-OR -

如果在找不到条目时不希望存在任何行:

insert into MyTable (Name, Code1, Code2)
select
  Name,
  substring(SomeCode1, 1, 5),
  SomeCode2
  from SomeTable
  where not isnull(SomeCode2) and SomeCode2 != '' and SomeCode2 != 'foo'
;