Update a table from two comma separated parameter as input

后端 未结 3 453
情深已故
情深已故 2021-01-23 00:43

I have a Gridview in front end where Grid have two columns : ID and Order like this:

 ID        Order

 1           1
 2           2
 3           3
 4                    


        
3条回答
  •  青春惊慌失措
    2021-01-23 01:42

    You could use a table valued parameter to avoid sending delimiter-separated values or even XML to the database. To do this you need to:

    1. Declare a parameter type in the database, like this:

      CREATE TYPE UpdateOrderType TABLE (ID int, Order int)
      
    2. After that you can define the procedure to use the parameter as

      CREATE PROCEDURE UpdateOrder (@UpdateOrderValues UpdateOrderType readonly)
      AS
      BEGIN
        UPDATE t
          SET OrderID = tvp.Order
          FROM  t
            INNER JOIN @UpdateOrderValues tvp ON t.ID=tvp.ID
      END
      

      As you can see, the SQL is trivial compared to parsing XML or delimited strings.

    3. Use the parameter from C#:

      using (SqlCommand command = connection.CreateCommand()) {
        command.CommandText = "dbo.UpdateOrder";
        command.CommandType = CommandType.StoredProcedure;
      
        //create a table from your gridview data
        DataTable paramValue = CreateDataTable(orderedData) 
        SqlParameter parameter = command.Parameters
                                  .AddWithValue("@UpdateOrderValues", paramValue );
        parameter.SqlDbType = SqlDbType.Structured;
        parameter.TypeName = "dbo.UpdateOrderType";
      
        command.ExecuteNonQuery();
      }
      

      where CreateDataTable is something like:

      //assuming the source data has ID and Order properties
      private static DataTable CreateDataTable(IEnumerable source) {
        DataTable table = new DataTable();
        table.Columns.Add("ID", typeof(int));
        table.Columns.Add("Order", typeof(int));
        foreach (OrderData data in source) {
            table.Rows.Add(data.ID, data.Order);
        }
        return table;
      }
      

      (code lifted from this question)

    As you can see this approach (specific to SQL-Server 2008 and up) makes it easier and more formal to pass in structured data as a parameter to a procedure. What's more, you're working with type safety all the way, so much of the parsing errors that tend to crop up in string/xml manipulation are not an issue.

提交回复
热议问题