程序中想实现一个小功能,再连接数据库后判断数据表是否存在,如存在就跳过创建表的函数,如不存在就创建数据表,已知表名,最好给点代码或例子,谢谢

解决方案 »

  1.   

    在程序中执行如下示例的SQL语句便可:
    --如果不存在表名为TableName的表
    if not exists(select * from dbo.sysobjects where id=object_id(N'[dbo].[TableName]') and OBJECTPROPERTY(id,N'IsUserTable' = 1))
    --就建立一个表名为TableName的表
    Create table [dbo].[TableName]
    {
        [UserId] [int] NULL--有一个int型的名为UserId的字段
    }
    Go
      

  2.   

    //正如楼上说所的 你可以这样做
    _bstr_t bstrSQL="select * from yourtable"
    bool  IsExistsYourTable(_bstr_t bstrSQL,CString  strSdbName)
    {
         try
    {
        if(m_pConnection==NULL)
                  OnInitADOConn(strSdbName);
    m_pRecordset.CreateInstance(__uuidof(Recordset));
                  m_pRecordset->Open(bstrSQL,m_pConnection.GetInterfacePtr(),adOpenDynamic,adLockOptimistic,adCmdText);
    }
        catch(_com_error e)
    {
     AfxMessageBox(e.Description());
             return false;
    }
          return true;
    }
      

  3.   


    各位,楼主都没有指明用到什么 DBMS ,你就怎么就能确定下面这句话有效?
    if not exists(select * from dbo.sysobjects where id=object_id(N'[dbo].[TableName]') and OBJECTPROPERTY(id,N'IsUserTable' = 1)) 这又不是标准的 SQL 语句,这只是 Microsoft SQL Server 的扩展语句。2、3 楼的方法就可以,当然结合 DBMS 还有很多方法。
      

  4.   

    我之前也做过这样的功能,不过不是用
    if not exists(select * from dbo.sysobjects where id=object_id(N'[dbo].[TableName]') and OBJECTPROPERTY(id,N'IsUserTable' = 1)) 
    这样的语句,而是直接在程序中去Creat TABLEname创表的方法,如果此表存在的话,程序就会报错,不过
    你在catch中得理一下就行了,让程序继续向正常的方向运行下去。
    所以这个还是很好实现的。
      

  5.   

    能解释下 dbo.sysobjects 表中的那些属性么?
    我不知道怎么设置这么where后面的条件