我使用以下代码设置调用存储过程的参数:
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);
代码段有效,但我想知道的是,是否有人找到了在新的SqlParameter构造函数中设置TypeName
的方法?我试着查看文档,但我唯一能找到的就是之后添加typename。
答案 0 :(得分:4)
您可以使用初始化程序完成此操作。下面的示例指定了强类型参数和变量值的最大长度,从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}
};
答案 1 :(得分:0)
尝试这样:
在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");
创建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 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