小弟初学,要查询数据库中是否有一张表(table_8),如果没有则建立这张表,并往其中写入数据,如果有则直接往里写入数据:
int TblCount;
select count(*) as TblCount from sysobjects where id=object_id('table_8') and xtype='U';
if(TblCount==0)
{
CREATE TABLE table_8(biaotou nchar(10),shijian datetime,weidu float,jingdu float,zhuangtai nchar(10));
insert   into   table_8 (shijian,weidu,jingdu,zhuangtai)   values   ( '%s','%s','%s','%s')  ,idatetime,latitude,longitude,status;
}
else 
{
insert   into   table_8 (shijian,weidu,jingdu,zhuangtai)   values   ( '%s','%s','%s','%s')  ,idatetime,latitude,longitude,status;
}
当数据库中没有表table_8时出错。

解决方案 »

  1.   

    if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[tb]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    begin
    CREATE TABLE [dbo].[tb] (
        [id] [char] (10) ,
            no varchar(10)
            PRIMARY KEY ([id] , no)

    go
    endinsert into tb ...select * from tb
      

  2.   

    我想问一下如果存在这个表(table_8),TblCount返回是0吗?不存在的话返回是什么?
      

  3.   


    if object_id('table_8') is not null
        begin
             insert into table_8 ....
        end
    else
        begin
           select * into table_8 from ....
        end
      

  4.   


    你这个是什么语言写法,sql server和c#都不是啊如果是c#你判断之前首先要取到count(*)的值啊,不能通过别名TblCount吧,别名和外面定义的TblCount 不相干的
      

  5.   

    if object_id('table_8') is not null
    drop table table_8
    go
    create table table_8
    (
    ...
    )
      

  6.   

    if object_id('table_8') is not null
    drop table table_8
      

  7.   


    --貌似是C++--mssql里思路这样
    if object_id('table_8') is not null
        insert into table_8 select * from ...
    else
        select ... into table_8 from ....