2012-01-09 104 views
0

我想檢查表是否沒有記錄,然後只在表中爲sql server和oracle插入3條記錄。檢查表是否沒有記錄,然後在表中插入3條記錄

+0

看起來很簡單(在同一個事務中,嘗試選擇一行,如果沒有,插入三個新的),你試過了什麼,爲什麼沒有工作? – Thilo 2012-01-09 10:07:27

+0

那是哪一個呢? Oracle或SQL Server? – Sathya 2012-01-09 10:12:51

+1

問題是Oracle和SQL Server有不同的語法。所以你將不得不爲PL/SQL和TSQL提供兩種不同的解決方案。除非您可以從另一個表中選擇三行,在這種情況下,純SQL解決方案是可行的,並且可以是跨平臺的。 – APC 2012-01-09 14:13:53

回答

0

什麼用這樣的問題..從部分

嘗試..

int count = select count(*) from table-name; 
if(count==0){ 
    //your insert statements as many as 
    insert into table-name values(); 
} 
0

您需要做的僅僅是這樣的:

IF (Select count(*) from tablename) = 0 
BEGIN 
    -- INSERT VALUES 
END 
0

,如果你想在單個插入句子中插入值,您可以這樣做:

insert into yourTable (yourFields) 
select value1 as yourField1, ... 
where (select count(*) from yourTable) =0 

Testing

create table #t (k int); 

insert into #t 
select 1 
where (select count(*) from #t) =0 

insert into #t 
select 2 as k; 

insert into #t 
select 3 
where (select count(*) from #t) =0 

select * from #t; 

注意,只有 '1' 和 '2' 被插入,而不是 '3'。

2

這種類型的結構將在SQL Server和Oracle工作:

SQL> insert into t34 
    2 select * from emp where id <= 3 
    3 and 0 in (select count(*) from t34) 
    4/

3 rows created. 

SQL> r 
    1 insert into t34 
    2 select * from emp where rownum <= 3 
    3* and 0 in (select count(*) from t34) 

0 rows created. 

SQL> 

但是否能解決你的問題實際上取決於你的三排的來源。

相關問題