dotnetspider.com
Login Login    Register      

TutorialsForumCareer DevelopmentResourcesReviewsJobsInterviewCommunitiesProjectsTraining

Subscribe to Subscribers
Talk to Webmaster
Tony John

Facebook
Google+
Twitter
LinkedIn
Online Membersbaskar
More...
Join our online Google+ community for Bloggers, Content Writers and Webmasters




Resources » Code Snippets » ADO.NET

Pass array to stored procedure


Posted Date:     Category: ADO.NET    
Author: Member Level: Gold    Points: 10



 


Simple Method to Pass Array to a Stored Procedure - SQL Server Side

Consider the following simple method for defining the stored procedure using dynamic SQL. The array parameter is defined simply as a string and the input will be expected to be comma-delimited. By forming the sql dyanmically with the input string, we can query against the values in the array by using the IN command.


CREATE PROCEDURE [dbo].[GetData]
@MyCodes as varchar(500) = '', -- comma delimited list of codes, ie: '''ABC'', ''DEF'', ''GHI'''
AS
BEGIN
DECLARE @query as nvarchar(500)

set @query = 'SELECT * FROM DATA WHERE Code IN (@p_MyCodes)'

exec SP_EXECUTESQL @query,
N'@p_MyCodes varchar(500)',
@p_MyCodes = @MyCodes
END


The above stored procedure definition will accept a comma-delimited string, which we process as an array using the SQL IN command. Note, we had to use dyanmic SQL to properly form the query (which involves expanding the comma-delimited string).

Simple Method to Pass Array to a Stored Procedure - C# .NET Side

Next, we need to define the method to pass the data and execute the stored procedure from C# .NET.

The first step is to convert our array of data into a comma-delimited string, which is what the stored procedure expects to receive. Depending on your data type, this code may vary. For this example, we are using a .NET collection.

string myCodes = string.Empty; // Initialize a string to hold the comma-delimited data as empty


foreach (MyItem item in MyCollection)
{
if (myCodes.Length > 0)
{
myCodes += ", "; // Add a comma if data already exists
}

myCodes += "'" + item.Name + "'";
}


The code above will create a string in the following format:
'One','Two','Three'

Now that the collection has been converted to a string, we can pass the value as a parameter to the stored procedure by using the following code:


using System;
using System.Data;
using System.Data.SqlClient;

SqlConnection MyConnection = null;
SqlDataReader MyReader = null;

try
{
// Create the SQL connection.
MyConnection = new SqlConnection("Server=(local);DataBase=Northwind;Integrated Security=SSPI"))
MyConnection.Open();

// Create the stored procedure command.
SqlCommand MyCommand = new SqlCommand("GetData", MyConnection);

// Set the command type property.
MyCommand.CommandType = CommandType.StoredProcedure;

// Pass the string (array) into the stored procedure.
MyCommand.Parameters.Add(new SqlParameter("@MyCodes", myCodes));

// Execute the command
MyReader = MyCommand.ExecuteReader();

// ...
}
catch (Exception excep)
{
}
finally
{
if (MyReader != null)
{
MyReader.Close();
MyReader.Dispose();
}

if (MyConnection != null)
{
MyConnection.Close();
MyConnection.Dispose();
}
}

Reference http://niksgaur.blogspot.com/2009/06/pass-array-to-stored-procedure.html





Did you like this resource? Share it with your friends and show your love!


Responses to "Pass array to stored procedure"
Author: Sushil Pugalia    17 Jul 2012Member Level: Bronze   Points : 0
How to pass int values as array? When I tried check codes with Int values, I got error: not able to convert to int.


Feedbacks      

Post Comment:




  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:   Sign In to fill automatically.
    Email: (Will not be published, but required to validate comment)



    Type the numbers and letters shown on the left.


    Next Resource: How to add identity column in Datatable
    Previous Resource: Linq with SQL Server(Display data in gridview using LINQ)
    Return to Resources
    Post New Resource
    Category: ADO.NET


    Post resources and earn money!
     
    More Resources
    Popular Tags   Tag posting guidelines   Search Tags  
    Stored procedure  .  Array  .  Ado.net  .  



    Follow us on Twitter: https://twitter.com/dotnetspider

    Active Members
    TodayLast 7 Daysmore...

    Awards & Gifts
    Email subscription
  • .NET Jobs
  • .NET Articles
  • .NET Forums
  • Articles Rss Feeds
    Forum Rss Feeds


    About Us    Contact Us    Copyright    Privacy Policy    Terms Of Use    Revenue Sharing sites   Advertise   Talk to Tony John
    Copyright © SpiderWorks Technologies Pvt Ltd., Kochi, India
    2005 - 2012 All Rights Reserved.
    .NET and other trademarks mentioned in this site belong to Microsoft and other respective trademark owners.
    Articles, tutorials and all other content offered here is for educational purpose only.
    We are not associated with Microsoft or its partners.