Table Value Parameter from c#

1.2k views Asked by At

I have read a number of articles and they all look like the following. When I execute from SSMS everything is fine. When I execute from c#, I get no exceptions. When I check the table, the c# did not insert.

CREATE TABLE dbo.Rates
    (Id BIGINT PRIMARY KEY IDENTITY, 
    LocationName NVARCHAR(50) NOT NULL, 
    CostRate INT NOT NULL);
GO

/* Create a table type. */
CREATE TYPE dbo.RatesType AS TABLE 
    ( LocationName NVARCHAR(50)
    , CostRate INT );
GO

/* Create a procedure to receive data for the table-valued parameter. */
CREATE PROCEDURE dbo.usp_InsertLocationRates
    @TVP RatesType READONLY
    AS 
    SET NOCOUNT ON
    INSERT INTO Rates
            (LocationName
            , CostRate)
        SELECT LocationName, CostRate
        FROM  @TVP;
GO

INSERT INTO dbo.Rates
        (LocationName
        , CostRate)
VALUES ( N'Costa Rica', 38)

DECLARE @T as dbo.RatesType
INSERT INTO @T(LocationName, CostRate)
VALUES('Equador', 24)
EXEC usp_InsertLocationRates @T;

SELECT * FROM DBO.Rates

Here is the c# that produces no error and no results.

try
{
    DataTable table = new DataTable("Items");
    table.Columns.Add("LocationName", typeof(string));
    table.Columns.Add("CostRate", typeof(int));    
    table.Rows.Add("Bali, Indonesia", 43);        

    using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["SampleDB"].ConnectionString))
    {
        connection.Open();

        var insertCommand = new SqlCommand("usp_InsertLocationRates", connection);
        var tableValueParameter = insertCommand.Parameters.AddWithValue("@TVP", table);
        tableValueParameter.SqlDbType = SqlDbType.Structured;
        tableValueParameter.TypeName = "RatesType";

        insertCommand.ExecuteNonQuery();
        connection.Close();
    }
}
catch (Exception e)
{
    // No error exists!
}

The results after running the SQL and then the c#:

Id  | LocationName  | CostRate
1   | Costa Rica    | 38
2   | Equador       | 24
2

There are 2 answers

0
Slippery Pete On BEST ANSWER

The default CommandType is Text; you need to specify that the command is for a stored procedure:

insertCommand.CommandType = CommandType.StoredProcedure;

After adding this your code works for me.

1
Sean Lange On

The problem is that you are using AddWithValue.

Try this instead.

insertCommand.Parameters.Add("@TVP", SqlDbType.Udt).Value = table;

You might also want to take a peek at this article. http://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/