如何将数据表插入SQL Server数据库表?
我已经从一些Excel文件中导入了数据,并将其保存到datatable。现在,我想将此信息保存在SQL Server数据库中。
我在网上看到了很多信息,但我听不懂:
- 有人说逐行插入另一个建议批量更新…等等:还有什么更好的?
 - 我应该使用
OLE或SQL Server对象(如dataAdapter或connection)吗? 
我需要从他的Excel文件中读取员工每周工作时间报告,并将其保存到保存所有报告的数据库表中(每周用新记录更新数据库)。
Excel文件仅包含当前一周的报告。
回答:
User-Defined TableType在您的数据库中创建一个:
CREATE TYPE [dbo].[MyTableType] AS TABLE(    [Id] int NOT NULL,
    [Name] [nvarchar](128) NULL
)
并在您的中定义一个参数Stored Procedure:
CREATE PROCEDURE [dbo].[InsertTable]    @myTableType MyTableType readonly
AS
BEGIN
    insert into [dbo].Records select * from @myTableType 
END
并将您的DataTable直接发送到sql server:
using (var command = new SqlCommand("InsertTable") {CommandType = CommandType.StoredProcedure}){
    var dt = new DataTable(); //create your own data table
    command.Parameters.Add(new SqlParameter("@myTableType", dt));
    SqlHelper.Exec(command);
}
要编辑存储过程中的值,可以声明具有相同类型的局部变量,然后将输入表插入其中:
DECLARE @modifiableTableType MyTableType INSERT INTO @modifiableTableType SELECT * FROM @myTableType
然后,您可以编辑@modifiableTableType:
UPDATE @modifiableTableType SET [Name] = 'new value'以上是 如何将数据表插入SQL Server数据库表? 的全部内容, 来源链接: utcz.com/qa/421889.html

