I have an MS SQL Server 2005 database. In a few procedures I have table parameters that I pass to a stored proc as an nvarchar (separated by commas) and internally divide into single values. I add it to the SQL command parameters list like this:
cmd.Parameters.Add("@Logins", SqlDbType.NVarchar).Value = "jim18,jenny1975,cosmo";
I have to migrate the database to SQL Server 2008. I know that there are table value parameters, and I know how to use them in stored procedures. But I don't know how to pass one to the parameters list in an SQL command.
Does anyone know correct syntax of the Parameters.Add
procedure? Or is there another way to pass this parameter?
DataTable
,DbDataReader
, orIEnumerable<SqlDataRecord>
objects can be used to populate a table-valued parameter per the MSDN article Table-Valued Parameters in SQL Server 2008 (ADO.NET).The following example illustrates using either a
DataTable
or anIEnumerable<SqlDataRecord>
:SQL Code:
C# Code:
The cleanest way to work with it. Assuming your table is a list of integers called "dbo.tvp_Int" (Customize for your own table type)
Create this extension method...
Now you can add a table valued parameter in one line anywhere simply by doing this:
Generic
Further to Ryan's answer you will also need to set the
DataColumn
'sOrdinal
property if you are dealing with atable-valued parameter
with multiple columns whose ordinals are not in alphabetical order.As an example, if you have the following table value that is used as a parameter in SQL:
You would need to order your columns as such in C#:
If you fail to do this you will get a parse error, failed to convert nvarchar to int.