结构化类型必须至少具有一个字段c#
作者:互联网
我真正想做的是将字符串数组发送到SQL Server.我正在使用SQL Server 2008.
可以将其标记为重复,但是从stactoverflow实现解决方案时,我面临着另一个问题
链接:How to pass an array into a SQL Server stored procedure
这是我的C#和存储过程代码
C#代码:
string[] str = new string[] {"s" , "a" , "k"};
DataTable dt = new DataTable();
dt.Columns.Add("names");
foreach (string item in str)
{
dt.Rows.Add(item);
}
foreach (DataRow r in dt.Rows)
{
Console.WriteLine(r["names"].ToString());
}
DataTable tvp = new DataTable();
SqlConnection conn = new SqlConnection("Data Source=SHZAK;Initial Catalog=synchroniztionTesing;Integrated Security=True");
conn.Open();
using (conn)
{
SqlCommand cmd = new SqlCommand("strpdPassAnStringArray", conn);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter tvparam = cmd.Parameters.AddWithValue("@List", tvp);
tvparam.SqlDbType = SqlDbType.Structured;
cmd.ExecuteScalar();
}
在进行存储过程之前,我创建了一个自定义类型:
CREATE TYPE dbo.arrayOfNames
AS TABLE
(
name nvarchar(max)
);
存储过程代码:
CREATE PROCEDURE [dbo].[strpdPassAnStringArray]
@List AS dbo.arrayOfNames READONLY
AS
BEGIN
SET NOCOUNT ON;
SELECT name FROM @List;
END
但是在应用程序代码中,它引发了这个异常:
There are not enough fields in the Structured type. Structured types must have at least one field.
在线
cmd.ExecuteScalar();
解决方法:
回答:
我很笨拙地问这个问题,但至少现在我知道是什么原因导致了这种异常
感谢@Gusman
如果您的DataTable像我一样是空的,则可以引发此异常
string[] str = new string[] {"sheraz" , "ahmed" , "khan"};
DataTable tvp = new DataTable();
tvp.Columns.Add("names");
foreach (string item in str)
{
tvp.Rows.Add(item);
}
foreach (DataRow r in tvp.Rows)
{
Console.WriteLine(r["names"].ToString());
}
SqlConnection conn = new SqlConnection("Data Source=SHZAK;Initial Catalog=synchroniztionTesing;Integrated Security=True");
conn.Open();
using (conn)
{
SqlCommand cmd = new SqlCommand("strpdPassAnStringArray", conn);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter tvparam = cmd.Parameters.AddWithValue("@List", tvp);
tvparam.SqlDbType = SqlDbType.Structured;
cmd.ExecuteScalar();
}
标签:table-variable,c,sql-server,stored-procedures 来源: https://codeday.me/bug/20191119/2032528.html