0

如何从存储过程插入表(用户定义类型)并传递给c#

表结构:

CREATE TABLE [dbo].[RegisterChoiceUserInitial](
    [RegisterChoiceUserInitialID] [int] IDENTITY(1,1) NOT NULL,
    [UserId] [uniqueidentifier] NOT NULL,
    [RegisterChoiceUserInitialJob] [nvarchar](50) NULL,
    [RegisterChoiceUserInitialOrganization] [nvarchar](50) NULL,
    [RegisterChoiceUserInitialUnit] [nvarchar](50) NULL,
    [RegisterChoiceUserInitialMembershipType] [nvarchar](50) NULL,
    [RegisterChoiceUserInitialStart] [nvarchar](10) NULL,
    [RegisterChoiceUserInitialEnd] [nvarchar](10) NULL,
 CONSTRAINT [PK_RegisterChoiceUserInitial] PRIMARY KEY CLUSTERED 
(
    [RegisterChoiceUserInitialID] ASC
)

用户自定义类型:

CREATE TYPE [dbo].[TableTypeInitial] AS TABLE(
    [ID] [int] NULL,
    [InitialJob] [nvarchar](50) NULL,
    [InitialOrganization] [nvarchar](50) NULL,
    [InitialUnit] [nvarchar](50) NULL,
    [InitialMembershipType] [nvarchar](50) NULL,
    [InitialMembershipStart] [nvarchar](10) NULL,
    [InitialMembershipEnd] [nvarchar](10) NULL
)
4

2 回答 2

0

无法将数据表作为输出参数返回。将表结果从 xp 返回到 c# 的唯一方法是使用 xml 参数或以下方式。

sql脚本:

create procedure sp_returnTable
    body of procedure
    **select * from RegisterChoiceUserInitial**
end

示例 C# 代码:

   string connString = "<your connection string>";
    string sql = "name of your sp";

SqlConnection conn = new SqlConnection(connString);

try {
   SqlDataAdapter da = new SqlDataAdapter();
   da.SelectCommand = new SqlCommand(sql, conn);
   da.SelectCommand.CommandType = CommandType.StoredProcedure;

   DataSet ds = new DataSet();   
   da.Fill(ds, "result_name");

   DataTable dt = ds.Tables["result_name"];

   foreach (DataRow row in dt.Rows) {
               //manipulate your data
   }

} catch(Exception e) {
   Console.WriteLine("Error: " + e);
} finally {
   conn.Close();
}
于 2012-05-03T07:07:10.530 回答
0

您应该为您的类型进行序列化/反序列化,并将序列化对象的字符串写入 SQL,然后当您需要获取它时,您从表中读取字符串并将其反序列化为您的类型。

编辑

关于序列化你可以在这里阅读csharp-tutorial-serialize-objects-to-a-file他们使用序列化到文件,但将其转换为字符串并不难

于 2012-05-02T14:04:28.073 回答