简体   繁体   中英

Can I set TypeName in the constructor of new SqlParameter when setting params for a stored procedure?

I am using the following code to set up parameters for a call to a stored procedure:

        List<SqlParameter> parameterList = new List<SqlParameter>();
        parameterList.Add(new SqlParameter("@Title", adminTest.Title));
        parameterList.Add(new SqlParameter("@Text", adminTest.Text));

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

The code snippet works but what I would like to know is if anyone found a way to set the TypeName in the new SqlParameter constructor? I tried looking at the documentation but the only thing I can find is adding the typename afterwards.

You can accomplish this with initializers. The example below specifies strongly-typed parameters and max length of variable values, which is a good practice from a SQL performance perspective.

    List<SqlParameter> parameterList = new List<SqlParameter>()
        {
            new SqlParameter("@Title", SqlDbType.VarChar) {Size = 30, Value = adminTest.Title},
            new SqlParameter("@Text", SqlDbType.VarChar) {Size = 30, Value = adminTest.Text},
            new SqlParameter("@Questions", SqlDbType.Structured) {TypeName = "dbo.QuestionList", Value = questions}
        };

try like this:

Create datatable in C#

 DataTable myDataTable = new DataTable("QuestionList");
    myDataTable.Columns.Add("Title", typeof(string));
    myDataTable.Columns.Add("Text", typeof(string));
    myDataTable.Rows.Add("Title", "Text1");
    myDataTable.Rows.Add("Text", "Text2");

Create sql parameter

  string conStr = "Server=localhost;Database=master;Trusted_Connection=True;";
        con = new SqlConnection(conStr);
        con.Open();
  using (con)
        {
            SqlCommand insertCommand = new SqlCommand("InsertQuestionList", con);
            SqlParameter tvpParam = insertCommand.Parameters.AddWithValue(
                "@QuestionList", myDataTable);
            insertCommand.CommandType = CommandType.StoredProcedure;

            tvpParam.SqlDbType = SqlDbType.Structured;
            tvpParam.TypeName = "dbo.QuestionList";
            tvpParam.Value = myDataTable;
            insertCommand.ExecuteNonQuery();
        }

        con.Close();

Create table type

 CREATE TYPE dbo.QuestionList AS TABLE
    ( Title varchar(50), TEXT nvarchar(50) )

PRODCEDURE to insert

ALTER PROCEDURE  InsertQuestionList
   @QuestionList QuestionList READONLY
AS
BEGIN
 --insert into Your table
 select * from @QuestionList
END
GO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM