如何将数组传递给存储过程

我在C#中有一个列表ClaimData ,它有三个项目日期,类型和描述这里可以有多行,如下所示,

ClaimData

Date Type Description 01/02/2012 "Medical" "Its a medical" 05/02/2013 "Theft" "Its a Theft" 01/02/2014 "Test" "Its a Test" 

我想将这整个数据传递给存储过程,一次性转到sql server,这样我就可以减少数据库的命中率。 我编写了存储过程,可以遍历此列表并将它们插入表中。

如何通过操作列表对象来实现可以作为参数传递给存储过程?

为了实现这一目标,您需要做一些事情,因为您的参数获得了创建表类型所需的多个值,并使您的存储过程接受该类型的参数。

由于您将TABLE作为参数传递,因此您需要创建一个TABLE TYPE,如下所示

表类型

 CREATE TYPE dbo.ClaimData AS TABLE ( [Date] DATE [Type] VARCHAR(50) [Description] VARCHAR(100) ) GO 

存储过程接受该类型参数

  CREATE PROCEDURE mainValues @TableParam ClaimData READONLY --<-- Accepts a parameter of that type AS -- Note it is ReadOnly BEGIN SET NOCOUNT ON; --Temp table to store the passed values -- since the passed parameter is only Read only and you -- cannot make any changes to the parameter so if you need to -- manipulate the data inside parameter you will need to get it -- into a Table vaiable. -- Declare a Table variable DECLARE @tmp_values table( [Date] DATE [Type] VARCHAR(50) [Description] VARCHAR(100) ); --Get values into that Table variable INSERT INTO @tmp_values ([Date],[Type],[Description]) SELECT [Date],[Type],[Description] FROM @TableParam -- Do other cool stuff with your passed data SELECT * FROM @tmp_values --<-- For testing purpose END 

执行PROC

声明该类型的变量并使用您的值填充它。

  DECLARE @Table ClaimData( --<-- Declare a variable of your type [Date] DATE [Type] VARCHAR(50) [Description] VARCHAR(100) ); -- Populate the variable INSERT INTO @Table ([Date],[Type],[Description]) SELECT [Date],[Type],[Description] FROM Source_Table EXECUTE mainValues @Table --<-- Stored Procedure Executed 

我使用字符串构建器和分隔符“|”将所有三列作为字符串发送

  DateString = '01/02/2012|05/02/2013|01/02/2014' TypeString = 'Medical|Theft|Test' DescString = "Its a medical|..." 

在数据库方面,我使用一个函数来分隔这些字符串,并将所有这些值插入临时表中。 这解决了我的问题。