检查表是否没有记录,然后在表中插入3条记录

时间:2012-01-09 10:04:51

标签: sql-server oracle

我想检查表是否没有记录,然后只在表中为sql server和oracle插入3条记录。

4 个答案:

答案 0 :(得分: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> 

但它是否可以解决你的问题实际上取决于你的三行的来源。

答案 1 :(得分:0)

这样做有什么问题..

尝试从你的角度......

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

答案 2 :(得分:0)

你只需要这样做:

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

答案 3 :(得分: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”。