buckshot
buckshot

Reputation: 315

SQL Server stored procedure not seeing parameter

I'm using C# to call a stored procedure and fill it from a datatable, but I'm doing something wrong.

My stored procedure:

CREATE PROCEDURE [dbo].[getStationInfo]
    @stationList AS dbo.udtableStationCode READONLY
AS  
BEGIN
    SELECT * 
    FROM stations
    WHERE StationCode IN (SELECT * FROM @stationList) 
END 

This procedure uses this user-defined table type:

CREATE TYPE [dbo].[udtableStationCode] 
     AS TABLE (StationCode NVARCHAR(50))

I'm trying to send a datatable to the stored procedure and get the result back in another datatable. Here's my C#:

    using (SqlConnection con = new SqlConnection(strConn))
    {
        con.Open();

        using (SqlCommand cmd = new SqlCommand("getStationInfo", con))
        {
            using (SqlDataAdapter ada = new SqlDataAdapter(cmd))
            {
                using (DataTable dtStationsReturned = new DataTable())
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Clear();
                    cmd.CommandText = "dbo.getStationInfo";
                    cmd.Parameters.AddWithValue("@stationList", dtStationCodes);
                    ada.Fill(dtStationsReturned);
                }
            }
        }
    }

No matter what I try, when my code gets to the 'ada.Fill' line, I get the error:

The procedure "getStationInfo" has no parameter named "@stationList".

But the stored procedure getStationInfo clearly DOES have that parameter. Can anyone tell me what I'm doing wrong? Any help appreciated.

EDIT: I've checked the contents of dtStationCodes, and it's fine.

EDIT: Here is how I am creating my dtStationCodes datatable:

DataTable dtStationCodes = new DataTable();
dtStationCodes.Columns.Add("StationCode", typeof(String));

Upvotes: 0

Views: 679

Answers (1)

pcdev
pcdev

Reputation: 3052

Try this:

using (SqlConnection con = new SqlConnection(strConn))
{
    con.Open();
    using (SqlCommand cmd = new SqlCommand("dbo.getStationInfo", con))
    {
        using (SqlDataAdapter ada = new SqlDataAdapter(cmd))
        {
            using (DataTable dtStationsReturned = new DataTable())
            {
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Clear();
                cmd.CommandText = "dbo.getStationInfo";
                SqlParameter sp = new SqlParameter("@stationList", dtStationCodes);
                sp.SqlDbType = SqlDbType.Structured;
                sp.TypeName = "dbo.udtableStationCode";
                cmd.Parameters.Add(sp);
                ada.Fill(dtStationsReturned);
            }
        }
    }
}

Refer to this question for another example of passing user defined table types.

Also see this page for more information on creating SqlParameters and passing TVPs to a stored procedure.

Upvotes: 2

Related Questions