2011-05-03 91 views
1

我通常儘量避免使用遊標並循環遍歷結果集,但是如何在下列情況下完成此操作,而不通過循環遍歷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。

回答

1
INSERT INTO MyTable (Name, Code1, Code2) 
SELECT Name, 
    CASE When coalesce(SomeCode2, '')='' Then NULL 
     When [email protected] Then NULL 
     Else substring(SomeCode1, 1, 5) 
, SomeCode2 
FROM SomeTable 
+0

不應該這是SUBSTR()而不是SUBSTRING()? – 2011-05-03 20:03:48

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; 
+0

歡迎。我已經格式化了您爲您提供的代碼。 – justkt 2011-05-03 20:07:41

+0

非常感謝! – 2011-05-03 20:12:13

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 
; 

- 或 -

如果你不希望任何行時都沒有發現條目存在:

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