Monday, July 7, 2014

use a Generic_Table_Type type in MSSQL

DECLARE @My_Table_Of_Ids Generic_Table_Type
INSERT INTO @My_Table_Of_Ids VALUES(4167)
EXEC Find_The_Aardvarks @My_Table_Of_Ids

 
 

Will allow one to speak into a sproc that starts out like this from MSSQL:

ALTER PROCEDURE [dbo].[Find_The_Aardvarks]
   (
      @My_Table_Of_Ids READONLY
   )
AS

 
 

The way to speak in from the C# side looks like this:

DataTable myTable = new DataTable("Whatever");
myTable.Columns.Add(new DataColumn("Id", typeof(int)));
foreach (var id in myCollectionFromElsewhere)
{
   var row = myTable.NewRow();
   row["Id"] = id;
   myTable.Rows.Add(row);
}
return ExecuteDataset("Find_The_Aardvarks", new[]
   {
      new SqlParameter("My_Table_Of_Ids", myTable) {SqlDbType =
            SqlDbType.Structured},
   });

 
 

Addendum 8/29/2018: The ALTER above should really look like this:

ALTER PROCEDURE [dbo].[Find_The_Aardvarks]
   (
      @My_Table_Of_Ids Generic_Table_Type READONLY
   )
AS

 
 

Note that Generic_Table_Type is a custom type and not something you should just expect to work at your database.

No comments:

Post a Comment