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

时间:2012-05-02 13:57:40

标签: c# sql sql-server-2008 c#-4.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
)

2 个答案:

答案 0 :(得分:0)

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

修改

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

答案 1 :(得分:0)

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

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();
}