[英]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? 该代码段有效,但是我想知道的是,是否有人找到了在新的SqlParameter构造函数中设置TypeName
的方法? 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. 下面的示例指定了强类型参数和变量值的最大长度,从SQL性能的角度来看,这是一个好习惯。
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# 在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 创建SQL参数
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.