I need to know if I need to add a sort column to my own table type, which I could use to sort, or if I can trust that the order of the parameters remains unchanged even without such a column.
This is my type:
CREATE TYPE [dbo].[VwdCodeList] AS TABLE( [VwdCode] [varchar](50) NOT NULL )
and this is one from sql where it is used:
as you can see, I use ROW_NUMBER to get the sort-column value.
Do I also need to add the sort column to the table type or ensure (documented) that it remains the same? This seems to work.
This is the ADO.NET code where I use it:
SqlParameter vwdCodeListParameter = insertWatchListCodeCommand.Parameters.Add("@VwdCodeList", SqlDbType.Structured); vwdCodeListParameter.TypeName = "[dbo].[VwdCodeList]"; vwdCodeListParameter.Value = WatchListSql.GetVwdCodeRecords(newVwdCodes, true); int inserted = insertWatchListCodeCommand.ExecuteNonQuery();
GetVwdCodeRecords returns an IEnumerable<SqlDataRecord> for an IEnumerable<string> .
Thanks to everyone. If the prospective reader is interested to know how I guaranteed the sort order. I changed the table type as suggested by adding another column:
CREATE TYPE [dbo].[VwdCodeList] AS TABLE( [VwdCode] [varchar](50) NOT NULL, [Sort] [smallint] NOT NULL )
Insert-sql is even simpler because sort-in columns are passed and not evaluated:
public const string InsertWatchListCodes = @" INSERT INTO [dbo].[WatchListCodes] ([WatchListID] ,[VwdCode] ,[Sort]) SELECT @WatchListID, cl.VwdCode, cl.Sort FROM @VwdCodeList cl;";
For completeness, here is a method that returns the value IEnumerable<SqlDataRecord> , used as the value for the table-valued parameter parameter (excluded error handling):
public static IEnumerable<SqlDataRecord> GetVwdCodeRecords(IEnumerable<string> vwdCodes, bool trimCode = true) { short currentSort = 0; foreach (string vwdCode in vwdCodes) { var record = new SqlDataRecord( new SqlMetaData("VwdCode", SqlDbType.VarChar, 50), new SqlMetaData("Sort", SqlDbType.SmallInt)); record.SetString(0, trimCode ? vwdCode.Trim() : vwdCode); record.SetInt16(1, ++currentSort); yield return record; } }