我有一个返回数据表值的方法,我想将它插入数据库中的表我该怎么办? 我的Methode:
public DataTable Import_To_Grid(string FilePath, string Extension)
{
string conStr = "";
switch (Extension)
{
case ".xls": //Excel 97-03
conStr = ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString;
break;
case ".xlsx": //Excel 07
conStr = ConfigurationManager.ConnectionStrings["Excel07ConString"].ConnectionString;
break;
}
conStr = String.Format(conStr, FilePath, "YES");
OleDbConnection connExcel = new OleDbConnection(conStr);
OleDbCommand cmdExcel = new OleDbCommand();
OleDbDataAdapter oda = new OleDbDataAdapter();
DataTable dt = new DataTable();
cmdExcel.Connection = connExcel;
//Get the name of First Sheet
connExcel.Open();
DataTable dtExcelSchema;
dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string SheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
connExcel.Close();
//Read Data from First Sheet
connExcel.Open();
cmdExcel.CommandText = "SELECT * From [" + SheetName + "]";
oda.SelectCommand = cmdExcel;
oda.Fill(dt);
connExcel.Close();
return dt;
}
我的数据库
CREATE TYPE udt_MyTable AS TABLE
(
[CID] BIGINT IDENTITY (1, 1) NOT NULL,
[CEmail] VARCHAR (250) NOT NULL,
[UID] INT NOT NULL,
[CName] NVARCHAR (450) NULL,
[CorpName] NVARCHAR (350) NULL,
[Password] BINARY (150) NULL)
CREATE PROCEDURE stp_MyProcedure
(
@TVP as dbo.udt_MyTable readonly -- NOTE: table valued parameteres must be readonly
)
AS
INSERT INTO [dbo].[TBLCustomers]
([CEmail]
,[UID]
,[CName]
,[CorpName]
,[Password])
SELECT
[CEmail]
,[UID]
,[CName]
,[CorpName]
,[Password]
FROM @TVP
我的代码:
using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.
ConnectionStrings["ZagmaDBConnectionString"].ConnectionString))
{
FileManagement FM = new FileManagement();
string ext = ".xls";
dt = FM.Import_To_Grid(Server.MapPath(FU.FileName), ext);
var cmd = new SqlCommand("stp_MyProcedure", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@TVP", SqlDbType.Structured).Value = dt;
cmd.ExecuteNonQuery();
}
我想知道如何使用此方法插入TBLCustomers
答案 0 :(得分:0)
Sql server 2008引入了一项名为Table valued parameters.的功能
想法是您创建一个user defined table type并将其用作存储过程的参数,允许您将表格结构数据发送到该存储过程。
.Net框架的ADO.Net完全支持这种参数类型,并且很容易使用。
所以,这是一个非常简单的例子,说明如何做到这一点。
首先,创建一个与您的数据表结构相匹配的UDT。由于它只是一个演示,我将展示一个只有2列的简单表:
CREATE TYPE udt_MyTable AS TABLE
(
@Id int,
@Text varchar(50)
)
然后您需要将该类型合并到存储过程中:
CREATE PROCEDURE stp_MyProcedure
(
@TVP as dbo.udt_MyTable readonly -- NOTE: table valued parameteres must be readonly
)
AS
INSERT INTO dbo.ActualTable (Id, Text)
SELECT Id, Text
FROM @TVP
GO
现在您需要做的就是执行c#代码中的过程:
using(var con = new SqlConnection(...))
{
var cmd = new SqlCommand("stp_MyProcedure", con);
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.Add("@TVP", SqlDbType.Structured).value = dt;
cmd.ExecuteNonQuery();
}
注意:表值参数是作为SqlDbType.Structured
传递给存储过程的.net数据表。