如何使用c#代码检查sql server中是否有表?

Par*_*tha 0 c# sql-server

我喜欢编写c#代码,我想通过它来检查sqlserver中是否有表?

任何人都可以给我一个示例代码吗?

Fre*_*örk 5

这个查询应该给你答案:

select count(id) from sysobjects where name = 'thetable' and type = 'U'
Run Code Online (Sandbox Code Playgroud)

如果count是1表存在,如果是0,则不存在.

包装成方法:

private bool TableExists(string tableName)
{
    using (SqlConnection conn = new SqlConnection(GetConnectionString()))
    {
        using (SqlCommand cmd = new SqlCommand("select count(id) from sysobjects where name = @tableName and type = 'U'", conn))
        {
            cmd.Parameters.AddWithValue("@tableName", tableName);
            conn.Open();
            int count = (int)cmd.ExecuteScalar();
            conn.Close();
            return count == 1;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)