Click here to Skip to main content
6,292,426 members and growing! (11,519 online)
Email Password   helpLost your password?
Database » Database » SQL Server     Intermediate License: The Code Project Open License (CPOL)

How to pass multiple records to a Stored Procedure

By Mika Wendelius

How to pass multiple records to a Stored Procedure in a single roundtrip.
C#, SQL, Windows, ADO.NET, SQL 2008, Dev
Posted:2 Dec 2008
Views:11,661
Bookmarked:41 times
Announcements
Loading...
 
Search    
Advanced Search
printPrint   Broken Article?Report       add Share
  Discuss Discuss   Recommend Article Email
18 votes for this article.
Popularity: 5.75 Rating: 4.58 out of 5
1 vote, 5.6%
1

2
1 vote, 5.6%
3
2 votes, 11.1%
4
14 votes, 77.8%
5

Introduction

This article describes how to use table-valued parameters when calling Stored Procedures. Table-valued parameters were introduced in SQL Server 2008. With this parameter type, a table with several rows can be passed to a Stored Procedure or a function. In some cases, this technique eliminates the need for several roundtrips between the client and the database, if the same procedure is called for several times but with different parameter values.

This article is not to be taken as an example of how to use SQL Server specific classes in C#, and certainly not as a coding style reference.

Type definitions

The example uses two types: ArtistType and RecordType. These types define the structure for parameters later. The definitions are:

-- Create the type for artist
CREATE TYPE ArtistType AS TABLE (
   [Artist#] int,
   [Name]    nvarchar(100)
);
-- Create the type for record
CREATE TYPE RecordType AS TABLE (
   [Record#] int,
   [Artist#] int,
   [Name]    nvarchar(100),
   [Year]    int
);

Table definitions

There are two target tables that are filled by a procedure. In this example, the data from the table isn't modified, but there's one trick: The client defines a primary key for each artist and record, and also a foreign key from the record to the artist. This information is used in the Stored Procedure, but the real primary keys in the database are auto-generated by SQL Server. The tables are:

-- Create artist table
CREATE TABLE Artist (
   [Artist#] int           NOT NULL IDENTITY(1,1) PRIMARY KEY,
   [Name]    nvarchar(100) NOT NULL
);
-- Create record table
CREATE TABLE Record (
   [Record#] int           NOT NULL IDENTITY(1,1) PRIMARY KEY,
   [Artist#] int           NOT NULL FOREIGN KEY REFERENCES Artist([Artist#]),
   [Name]    nvarchar(100) NOT NULL,
   [Year]    int           NULL
);

The procedure

The procedure consists of two loops. The outer loop fetches each artist and inserts it into the database. After that, it takes the identity given to the new row. After this, all the records from this single artist are fetched, and the foreign key is set to the corresponding primary key in the artist table.

CREATE PROCEDURE [dbo].[AddShoppings](
   @Artists dbo.ArtistType READONLY,
   @Records dbo.RecordType READONLY) AS
BEGIN
   -- variables to use
   DECLARE @artist         int;
   DECLARE @artistIdentity int;
   DECLARE @name           varchar(100);
   DECLARE @year           int;

   -- cursor for artists parameter
   DECLARE artistCursor CURSOR FOR 
        SELECT [Artist#], [Name]
        FROM @Artists;

   -- loop through artists
   OPEN artistCursor;
   FETCH NEXT FROM artistCursor INTO @artist, @name;
   WHILE @@FETCH_STATUS = 0
   BEGIN
      -- insert the artist
      INSERT INTO Artist ([Name]) VALUES (@name);
      SET @artistIdentity= @@IDENTITY;

      -- cursor for records parameter
      DECLARE recordsCursor CURSOR FOR 
         SELECT [Name], [Year]
         FROM @Records
         WHERE [Artist#] = @artist;

      -- fetch records and insert them
      OPEN recordsCursor;
      FETCH NEXT FROM recordsCursor INTO @name, @year;
      WHILE @@FETCH_STATUS = 0
      BEGIN
         INSERT INTO Record ([Artist#], [Name], [Year]) 
            VALUES (@artistIdentity, @name, @year);
         FETCH NEXT FROM recordsCursor INTO @name, @year;
      END;
      CLOSE recordsCursor;
      DEALLOCATE recordsCursor;

      FETCH NEXT FROM artistCursor INTO @artist, @name;
   END;
   CLOSE artistCursor;

   -- clean-up
   DEALLOCATE artistCursor;
END;

The C# code

The program is a simple console application. It:

  • Builds and fills data tables for Artist and Record
  • Creates a connection
  • Creates the database objects
  • Begins a transaction
  • Calls the procedure
  • Commits work

In order to use the code, you need to install a SQL Server 2008 instance and create a database in it. After that, the SQL Server instance name and database name are configured via app.config. It would look something like:

...
<applicationSettings>
    <TableValuedParameters.Properties.Settings>
        <setting name="DataSource" serializeAs="String">
            <value>MyMachine\SqlServerInstanceName</value>
        </setting>
        <setting name="DatabaseName" serializeAs="String">
            <value>DatabaseNameToUse</value>
        </setting>
    </TableValuedParameters.Properties.Settings>
</applicationSettings>
...

The actual call to the database is simple. The keyword for the parameters is System.Data.SqlDbType.Structured. This tells the SQL client that the data is in table format, and based on this, a DataTable object with all of its contents can be used as a parameter:

command.CommandText = "AddShoppings";
command.CommandType =  System.Data.CommandType.StoredProcedure;

parameter = command.Parameters.AddWithValue("@Artists", artist);
parameter.SqlDbType = System.Data.SqlDbType.Structured;

parameter = command.Parameters.AddWithValue("@Records", record);
parameter.SqlDbType = System.Data.SqlDbType.Structured;

command.Transaction = transaction;
command.ExecuteNonQuery();

That's about it. The rest of the logic is in the code sample. Enjoy!

History

  • December 2, 2008: Created.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Mika Wendelius


Member
I've been a programmer since mid 80's using languages like assembler, C/C++, PL/I (mainframe environment), pascal, VB (I know, I know, no comments please) and C# and utilizing different techniques and tools.

However I'm specialized in databases and database modeling. Mostly I have used products like Oracle (from version 6), SQL Server (from version 4.2), DB2 and Solid Server (nowadays an IBM product).

For the past 10 years my main concerns have been dealing with different business processes and how to create software to implement them. At my spare time (what ever it is) I'm also teaching and consulting different areas on database management and database oriented software design.
Occupation: Architect
Location: Finland Finland

Other popular Database articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 16 of 16 (Total in Forum: 16) (Refresh)FirstPrevNext
GeneralDon't Use @@Identity PinmemberKevinAG12:54 9 Dec '08  
GeneralRe: Don't Use @@Identity PinmemberMika Wendelius11:11 10 Dec '08  
GeneralCursors? Pinmemberneil_b23:01 8 Dec '08  
GeneralRe: Cursors? PinmemberMika Wendelius6:23 9 Dec '08  
GeneralTry this if you want a solution for SQL 2000 PinmemberMuffadal0:51 3 Dec '08  
GeneralRe: Try this if you want a solution for SQL 2000 PinmemberMika Wendelius8:30 3 Dec '08  
GeneralMy vote of 1 PinmemberParesh Gheewala20:31 2 Dec '08  
QuestionRe: My vote of 1 PinmemberHamed Mosavi20:52 2 Dec '08  
GeneralGreat Article PinmemberNagaraj Muthuchamy19:48 2 Dec '08  
GeneralRe: Great Article PinmemberMika Wendelius8:28 3 Dec '08  
GeneralBrilliant! PinmemberHamed Mosavi19:35 2 Dec '08  
GeneralRe: Brilliant! PinmemberMika Wendelius19:45 2 Dec '08  
GeneralMy vote of 5 PinmemberN a v a n e e t h17:40 2 Dec '08  
GeneralRe: My vote of 5 PinmemberMika Wendelius19:13 2 Dec '08  
GeneralAh bugger PinmemberMycroft Holmes15:07 2 Dec '08  
GeneralRe: Ah bugger PinmemberMika Wendelius19:22 2 Dec '08  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 2 Dec 2008
Editor: Smitha Vijayan
Copyright 2008 by Mika Wendelius
Everything else Copyright © CodeProject, 1999-2009
Web18 | Advertise on the Code Project