Samantha J T Star
Samantha J T Star

Reputation: 32758

How can I set the value and the datatype when creating a new SqlParameter?

I have my code setting up a parameter for QuestionsCount and then for Questions:

    parameterList.Add(new SqlParameter("@QuestionsCount", chunkSize));

    var p = new SqlParameter("@Questions", questions);
    p.TypeName = "dbo.QuestionList";
    parameterList.Add(p);

Is there a way that I can combine the last three lines and create a new SqlParameter with the typeName. I was looking at the definitions but cannot find one that takes the value (questions) and the TypeName "dbo.QuestionList".

Upvotes: 1

Views: 801

Answers (2)

Dan Guzman
Dan Guzman

Reputation: 46203

One method is with an initializer to supply property values not available in the constructor overloads:

parameterList.Add(new SqlParameter( "@Questions", SqlDbType.Structured ) { TypeName = "dbo.QuestionList", Value = questions });

Upvotes: 1

marc_s
marc_s

Reputation: 754268

There are quite a few overloads for the constructor for SqlParameter, some of which allow you to specify a datatype and optionally a length:

var p = new SqlParameter("@Questions", SqlDbType.VarChar, 100);
p.Value = ":.......";
parameterList.Add(p);

Check out the MSDN documentation on SqlParameter for details.

Upvotes: 3

Related Questions