【问题标题】:how to check if a row or column is already present in the table while inserting or updating the table如何在插入或更新表时检查表中是否已存在行或列
【发布时间】:2012-09-06 07:03:12
【问题描述】:

我正在构建一个项目,在该项目中我可以访问数据库表,向表中插入和更新行和列。

我正在使用GridView 更新数据库中的一个表,我每次都使用它向另一个表添加新列。

我在 button_Click 上的代码是:

com = new SqlCommand("ALTER TABLE Location_Profile_Master ADD " + LocProName.Text + " int", con);
            con.Open();
            com.ExecuteNonQuery();
            con.Close();

            foreach (GridViewRow row in GridView1.Rows)
            {
                string Pro_Name = row.Cells[1].Text;

                for (int i = 1; i < GridView1.Columns.Count; i++)
                {
                    int n = Convert.ToInt16(row.Cells[i + 1].Text);
                    //short n = 0;
                    //if (Int16.TryParse(row.Cells[i + 1].Text, out n))
                    //{
                        com = new SqlCommand("UPDATE Location_Profile_Master SET " + LocProName.Text + "='" + n + "' WHERE Profile_Name='" + Pro_Name.ToString().Trim() + "' ", con);
                        con.Open();
                        com.ExecuteNonQuery();
                        con.Close();
                    //}
                }

            }

因此,在添加列及其值时,我想检查该列名是否已经存在于数据库中,如果不存在,我想检查列值是否已经存在于数据库中。应通知用户该列已存在于数据库中。

另外,当我插入一行时,我想知道该行是否已经存在于表中。

请帮忙。

【问题讨论】:

    标签: c# asp.net sql


    【解决方案1】:

    您可以直接在Information Schema Views 中读取MS SQL-Server 中的架构信息,也可以使用DataReader.ExecuteReader(CommandBehavior.SchemaOnly) 来检索给定表的架构信息:

    DataTable schema;
    using (var con = new System.Data.SqlClient.SqlConnection(conStr))
    {
        var getSchemaSql = String.Format("SELECT * FROM {0}", tableName);
        using (var schemaCommand = new System.Data.SqlClient.SqlCommand(getSchemaSql, con))
        {
            con.Open();
            using (var reader = schemaCommand.ExecuteReader(CommandBehavior.SchemaOnly))
            {
                schema = reader.GetSchemaTable();
            }
        }
    }
    

    然后是类似的东西:

    for (int rowIndex = 0; rowIndex < schema.Rows.Count; rowIndex ++)
    {
        DataRow schemaRow = schema.Rows[rowIndex];
        String columnName = schemaRow.Field<String>("ColumnName");
        Type dataType = schemaRow.Field<Type>("DataType");
        Int32 columnSize = schemaRow.Field<Int32>("ColumnSize");
        if (dataType.FullName == "System.String")
        {
            // ...
        } 
     }
    

    或者,如果您只是想检查该表中是否存在给定的列名:

    String colName = "Column1";
    bool exists = schema.AsEnumerable()
                        .Any(r => r.Field<String>("ColumnName") == colName);
    

    如果你想知道一行是否已经存在,你可以在sql中使用它的主键/标识符和EXISTS

    IF NOT EXISTS(SELECT 1 FROM Location_Profile_Master WHERE PROFILE_NAME=@ProfileName)
    

    【讨论】:

      【解决方案2】:

      我假设您使用的是 MS SQL Server。试试这个代码来检查列是否存在,并在里面验证行是否存在:

      IF EXISTS(SELECT * FROM SYS.COLUMNS WHERE Name = N'columnName'  
                  AND Object_ID = Object_ID(N'Location_Profile_Master'))
      BEGIN
          -- Column Exists
          IF EXISTS (SELECT Profile_Name FROM Location_Profile_Master WHERE Profile_Name = @yourValue)
          BEGIN
              --value exists
          END
      END
      

      【讨论】:

        【解决方案3】:

        首先一个建议:使用参数而不是值"'" + "'",因为它对 SQL 注入很敏感。

        要在数据库中检查列是否存在,您可以使用:

        SELECT CASE  WHEN COL_LENGTH('tableName', 'columnName') IS NOT NULL 
        THEN 1 ELSE 0 END AS isExists
        

        即使数据库中不存在该表,这也会给你一个 0

        【讨论】:

          【解决方案4】:

          你最好为这样的事情创建一个存储过程:

          IF EXISTS ( SELECT 1 
                      FROM INFORMATION_SCHEMA.COLUMNS 
                      WHERE TABLE_NAME = 'Location_Profile_Master' 
                        AND Column_Name = @columnParam) 
          BEGIN
              -- The column exists
          END
          ELSE
              -- The column doesn't exit
          

          【讨论】:

            猜你喜欢
            • 2018-02-25
            • 2017-04-14
            • 2020-12-29
            • 1970-01-01
            • 2012-09-16
            • 1970-01-01
            • 2015-12-18
            • 2012-07-26
            • 1970-01-01
            相关资源
            最近更新 更多