Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to send a collection of ID's as a ADO.NET SQL parameter?

Tags:

Eg. can I write something like this code:

public void InactiveCustomers(IEnumerable<Guid> customerIDs)
{
    //...
    myAdoCommand.CommandText =
        "UPDATE Customer SET Active = 0 WHERE CustomerID in (@CustomerIDs)";
    myAdoCommand.Parameters["@CustomerIDs"].Value = customerIDs;
    //...
}

The only way I know is to Join my IEnumerable and then use string concatenation to build my SQL string.

like image 424
Thomas Jespersen Avatar asked Sep 22 '08 12:09

Thomas Jespersen


People also ask

What is parameter in Ado net?

ADO.NET wraps a class around the parameters used for each column of the database. You can use the parameters in conjunction with SelectCommand to help you to select data for the DataSet.

What is ADO NET SQL?

ADO.NET is the core data access technology for . NET languages. Use the Microsoft. Data. SqlClient namespace to access SQL Server, or providers from other suppliers to access their stores.

Which object is used to pass variable to Sqlcommand?

Command objects use parameters to pass values to SQL statements or stored procedures, providing type checking and validation. Unlike command text, parameter input is treated as a literal value, not as executable code.

How do I connect to a stored procedure in Ado net?

You has to provide the connection string as a parameter which includes the Data Source name, the database name and the authentication credentials. Open the connection using the Open() method. SqlConnection con = new SqlConnection("Data Source= ; initial catalog= Northwind ; User Id= ; Password= '"); con. open();


2 Answers

Generally the way that you do this is to pass in a comma-separated list of values, and within your stored procedure, parse the list out and insert it into a temp table, which you can then use for joins. As of Sql Server 2005, this is standard practice for dealing with parameters that need to hold arrays.

Here's a good article on various ways to deal with this problem:

Passing a list/array to an SQL Server stored procedure

But for Sql Server 2008, we finally get to pass table variables into procedures, by first defining the table as a custom type.

There is a good description of this (and more 2008 features) in this article:

Introduction to New T-SQL Programmability Features in SQL Server 2008

like image 91
Eric Z Beard Avatar answered Oct 12 '22 15:10

Eric Z Beard


You can with SQL 2008. It hasn't been out very long, but it is available.

like image 39
Jonathan Rupp Avatar answered Oct 12 '22 14:10

Jonathan Rupp