SQL Server中判断数据库是否存在:
select * From master.dbo.sysdatabases where name='pubs'
最初安装 SQL Server 时,sysdatabases 包含 master、model、msdb、mssqlweb 和 tempdb 数据库的项。该表只存储在 master 数据库中。
但在实际使用中,需判断Status状态位:
其中某些状态位可由用户使用 sp_dboption(read only、dbo use only、single user 等)进行设置:
1 = autoclose;使用 sp_dboption 设置。数据库完全关闭,其资源在最后一个用户注销后释放。
4 = select into/bulkcopy;使用 sp_dboption 设置。允许使用 Select INTO 语句和快速大容量复制。
8 = trunc. log on chkpt;使用 sp_dboption 设置。如果数据库处于日志截断模式,则检查点将截断日志中非活动的部分。只能为 master 数据库设置此选项。16 = torn page detection,使用 sp_dboption 设置。可以检测残缺页。
32 = loading。
64 = pre recovery。
128 = recovering。
256 = not recovered。
512 = offline;使用sp_dboption 设置。数据库将处于脱机状态。
1024 = read only;使用 sp_dboption 设置。用户仅能读取数据库中的数据而无法对其进行修改。
2048 = dbo use only;使用sp_dboption 设置。只有数据库所有者可以使用数据库。
4096 = single user;使用 sp_dboption 设置。每次只能有一个用户访问数据库。
32768 = emergency mode。
4194304 = autoshrink。
1073741824 = cleanly shutdown。
可以同时打开多个位。
譬如:判断一个数据库是否offline
select * From master.dbo.sysdatabases where name='pubs' and status<>512
SQL Server中判断表对象是否存在:
select count(*) from sysobjects where id = object_id('数据库名.Owner.表名')
首先连接数据库,连接数据库后,使用下面函数即可,判断数据库中的表属否存在,存在返回true,否则返回false。
BOOL IsTableExsist(CString strTableName)
{
try
{
_ConnectionPtr pConnection = NULL; //添加一个指向Connection对象的指针
CStringArray arrTableNames;
_RecordsetPtr Recordset = pConnection->OpenSchema(adSchemaTables);
_variant_t vDBTableName;
_bstr_t bstrTableType;
while(!Recordset->adoEOF)
{
vDBTableName = Recordset->GetCollect("TABLE_NAME");
bstrTableType = Recordset->GetCollect("TABLE_TYPE");
if((bstrTableType == (_bstr_t)"TABLE") || (bstrTableType == (_bstr_t)"VIEWS"))
{
arrTableNames.Add((char*)_bstr_t(vDBTableName));
}
Recordset->MoveNext();
}
int iCount = arrTableNames.GetSize();
for (int i=0; i < iCount; i++)
{
CString& strName = arrTableNames[i];
if (strName == strTableName)
return TRUE;
}
}
catch(_com_error& e)
{
CString str;
str.Format("文件名称: %s /n 所在代码行 : %d 执行SQL语句失败 错误原因 %s" , __FILE__ , __LINE__ , (LPCSTR)e.Description());
TRACE(str);
AfxMessageBox(str);
return FALSE;
}
return FALSE;
}