检查数据库中是否存在行,列等的有效方法?

时间:2018-06-15 08:13:40

标签: c# winforms sql-server-2008 visual-studio-2015

我一直在使用以下代码来检查SQL Server数据库中是否存在特定的行,列,表等。我想知道是否有更有效的方法来做到这一点 Note1: I am particularly trying to eliminate using the dataTable dt_local.
Note2: I am using C#, WinForms, VS-2015 and SQL Server 2008 R2 Express.

internal static bool MaujoodHaiKya(string queryLe)
    {
        //This function has been created to check
        //if a particular row, column, table etc exists
        //and to return true or false accordingly
        try
        {
            DataTable dt_local = new DataTable();
            string[] connString = System.IO.File.ReadAllLines(Application.StartupPath + "\\MM.ini");

            using (SqlConnection conn = new SqlConnection(connString[1]))
            {
                SqlCommand cmd = new SqlCommand(queryLe, conn);
                SqlDataAdapter adapter = new SqlDataAdapter();

                conn.Open();
                adapter.SelectCommand = cmd;
                adapter.Fill(dt_local);
            }
            return (true); //Column exists
        }
        catch
        {
            return (false); //Column does not exist
        }
    }

2 个答案:

答案 0 :(得分:2)

这里最好的选择可能是使用数据库元数据而不是数据查询。考虑:

select count(1) as [Count] from sys.columns
where [object_id] = object_id('PRH') and [name] = 'ACTIV'

如果列不存在,则返回0。有了它,你可以使用:

cmd.CommandText = @"
    select count(1) as [Count] from sys.columns
    where [object_id] = object_id('PRH') and [name] = 'ACTIV'";

int count = (int)cmd.ExecuteScalar();
return count == 1;

请注意,如果需要,可以参数化此查询:

cmd.CommandText = @"
    select count(1) as [Count] from sys.columns
    where [object_id] = object_id(@table) and [name] = @column";
cmd.Parameters.AddWithValue("@table", tableName);
cmd.Parameters.AddWithValue("@column", columnName);

对信息架构做同样的事情:

select COUNT(1) as [Count] from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME = 'PRH' and COLUMN_NAME = 'ACTIV'

(也可以参数化)

答案 1 :(得分:1)

您有一些替代选择 - 可能会或可能不会更有效。真正知道的唯一方法是测试它。这是我头脑中的两个:

  1. 使用COL_LENGTH T-SQL函数查询数据库元数据 - 查看给定表中给定列的长度是否为NULL

    IF COL_LENGTH('table_name','column_name')为空 开始  / 列不存在或调用者没有查看对象的权限 / END

    有关详细信息,请参阅此处:How to check if a column exists in a SQL Server table?

  2. 执行简单的"select top 1 * from <tablename>"查询,将其加载到数据表中并枚举字段,检查您要查找的字段是否已返回。