怎么判断数据库中是否含有某个表

2024-11-28 01:54:19
推荐回答(1个)
回答(1):

///


/// 执行一条计算查询结果语句,返回查询结果(object)。
///

/// 计算查询结果语句
/// 查询结果(object)
public static object GetSingle(string SQLString)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand(SQLString, connection))
{
try
{
connection.Open();
object obj = cmd.ExecuteScalar();
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
return null;
}
else
{
return obj;
}
}
catch (System.Data.SqlClient.SqlException e)
{
connection.Close();
throw e;
}
}
}
}

///
/// 判断是否存在某表
///

/// 表名称
/// 是否存在
public static bool ColumnExists(string tableName)
{
string sql = "select count(1) from syscolumns where [id]=object_id('" + tableName + "') ";
object res = GetSingle(sql);
if (res == null)
{
return false;
}
return Convert.ToInt32(res) > 0;
}

connectionString 是数据库链接字符串
直接复制粘贴就可以用