我有两张表TAB1
和TAB2
。我想在TAB2
中的特定列中插入数据。我想在TAB1
条件下插入必须从WHERE
获取的数据。如果存在有问题的数据,则在TAB2
中插入数据。如果不是,请在TAB2
这里我只谈论单列。我也插入了一些其他数据。它可以作为单个SQL查询发生。我正在使用Oracle。
这是我的演示代码。我需要这样的东西:
INSERT INTO TAB1('value1','value2',?)
if exists(select king from TAB2 where queen='yash' )
?=select king from TAB2 where queen='yash'
if not exists
?=''
TAB1
和TAB2
具有不同类型的列。
TAB1 TAB2
-------- -----------------
col1 col2 col3 col4 col1 king Queen
----------------- ----------------
1 jan King Robin 1 Alex yash
2 Feb King2 Hood 2 Jhon Shakthi
现在我想在TAB2中使用where condition插入TAB1中的数据 像这样的东西
insert into TAB1(col1,col2,col3,col4)
values(5,'MArch',King7, select king From TAB2 where Queen='yash')
如果选择来自TAB2的国王Queen='yash'
返回'Alex'
,则必须插入,如果不是必须插入空值。
Here Queen column is Unique column .. So you can expect single row data only.
TAB1 and TAB2 having different column names and different column Types
答案 0 :(得分:4)
TAB2
-----------------
col1 king Queen
----------------
1 Alex yash
2 Jhon Shakthi
3 Fred Maya
insert into TAB1(col1,col2,col3,col4, col5)
select 5, -- If you are tring to use an auto incremental value, I recommend you to use a trigger and Sequence on the table
'March',
'King7',
king ,
col1 -- Col1 is used to get an Idea which row caused the Insert
From
TAB2 where Queen='yash';
TAB1
--------------------------------
col1 col2 col3 col4 col5
--------------------------------
5 March King7 Alex 1
insert into TAB1(col1,col2,col3,col4, col5)
select 5,
'March',
'King7',
case when Queen='yash' then king else '' end,
col1
From
TAB2 ;
--------------------------------
col1 col2 col3 col4 col5
--------------------------------
5 March King7 Alex 1
5 March King7 '' 2
5 March King7 '' 3
---- removing insert to Col5 column
insert into TAB1(col1,col2,col3,col4)
select
distinct
5,
'March',
'King7',
case when Queen='yash' then king else '' end
From
TAB2 ;
--------------------------
col1 col2 col3 col4
--------------------------
5 March King7 Alex
5 March King7 ''
insert into TAB1(col1,col2,col3,col4)
select
distinct
5,
case when Queen='yash' then 'March' else '' end,
case when Queen='yash' then 'King7' else '' end,
case when Queen='yash' then king else '' end
From
TAB2 ;
--------------------------
col1 col2 col3 col4
--------------------------
5 March King7 Alex
5 '' '' ''
答案 1 :(得分:0)
假设通过'insert blank'表示不执行插入操作,您可能希望查看执行INSERT SELECT。
INSERT INTO TAB1( ... )
SELECT ... FROM TAB2
WHERE ...