我已经从一些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'
关于c# - 如何将数据表插入SQL Server数据库表?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9075159/