2012-01-09 117 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> 

但是否能解决你的问题实际上取决于你的三排的来源。

相关问题