我有一種方法返回一個數據表值,我想將它插入到數據庫中的表中我應該怎麼做? 我了Methode:如何使用數據表添加一個.xls到數據庫
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
你的數據表是否有固定的結構(我的意思是,總是有相同的列)?另外,你正在使用哪個版本的sql server? –
1.yes我的表是固定的2.sql-server 2008 R2 – sadeq