¿Cuáles son las mejores formas de enviar matrices desde js (jQuery) a sql sproc? Matriz de transmisión entre capas

Array transmitting between layers.

What are the best ways to send arrays from js (jQuery) to sql sproc? Could you share your ideas?

This generalizes my previous questions:

  1. Js to MVC controller.

    https://stackoverflow.com/a/9109671/1145224

  2. Best way to send arrays from MVC to SQL. (Is still open for discussion)

  3. And this interesting SQL post for testing. What about [Table Valued Parameters]?

    http://www.adathedev.co.uk/2010/02/sql-server-2008-table-valued-parameters.html

preguntado el 02 de febrero de 12 a las 10:02

1 Respuestas

I think that best way is to send array as Parámetro con valores de tabla

How to pass an array to SP from MVC (any c# code). In your case it is a int[] array, right?

public static DataTable ConvertIntArrayToDataTable(IEnumerable<int> array, bool AllowNull = false)
{
    var dt = new DataTable();
    dt.Columns.Add(new DataColumn("Value", typeof(int)) { AllowDBNull = AllowNull });
    foreach(var i in array)
      dt.Rows.Add(i));
    return dt;
}   

You also have to implement Tipo de tabla definido por el usuario

CREATE TYPE IntArray AS TABLE
(
  Value int not null
)

Create procedure which accepts this parameter:

CREATE PROCEDURE YourProc
  @DataArray IntArray READONLY
AS
BEGIN
  SELECT Value FROM @DataArray
END

and finally call the proc with approptiate parameter:

void CallProc(int[] array)
{
// assuming there is exisis already created connection and command named sqlCommand

  sqlCommand.CommandText = "YourProc";
  sqlCommand.CommandType = CommandType.StoredProcedure;
  sqlCommand.Parameters.Clear();
  sqlCommand.AddWithValue("@DataArray", ConvertIntArrayToDataTable(array));
  sqlCommand.ExecuteNonQuery();
}

Respondido 02 Feb 12, 15:02

wow, that is perfect! clear and understandable. thank you so much! - Anton Lyhin

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.