Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to pass an array to stored procedure

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 183
    Comment on it

    Stored procedure is used to store a SET of SQL statements in database as a compiled form which can be used by different programs. It performs a special task like inserting data into database, deleting records from database or updating an existing record in the database.

     

    To pass an array to stored procedure steps are given below:

    1. Create a user defined table type using below code in SQL server 

    CREATE TYPE [dbo].[book]
    
             AS TABLE
    
                    (
                           Title NVARCHAR(max)
    
                       );

     

    2. Create a stored procedure using below code:

    CREATE PROC book_InsertSP
    
             @ARRAY_book AS dbo.book READONLY
    
              AS
    
              BEGIN
    
                    INSERT INTO [dbo].[book](Title) SELECT * FROM @ARRAY_book
    
              END

     

    3. Add the following namespace:    

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

     

    4. Add the following C# code:

    string book = "Book1, Book2, Book3, Book4";
    
    string[] books = book.Split(',');
    
    DataTable dt_books = new DataTable();
    
    dt_books.Columns.Add("book", typeof(String));
    
    DataRow wr;
    
    foreach(string b in books)
    
      {
    
           wr= dt_books.NewRow();
    
           wr["Title"] = b.Trim();
    
            dt_books.Rows.Add(wr);
    
       }
    
    string connectionString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
    
    try
    
     {
    
           using (SqlConnection con = new SqlConnection(connectionString))
    
            {
    
                 SqlCommand cmd = new SqlCommand("book_InsertSP", connectionObject);
    
                 cmd.CommandType = CommandType.StoredProcedure;
    
                 SqlParameter tvparam = cmd.Parameters.AddWithValue("@ARRAY_book", dt_books);
    
                 tvparam.SqlDbType = SqlDbType.Structured;
    
                 cmd.ExecuteNonQuery();
    
            }
    
      }
    
    catch(Exception e)
    
      {
    
          throw ex;
    
      }

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: