2015-02-23 62 views

回答

0

假设你有一个这样的表:

CREATE TABLE dbo.FileTest 
(
    ID INT NOT NULL IDENTITY(1,1), 
    FileName VARCHAR(255), 
    DateInserted DATETIME2(3) 
) 

然后,你需要创建一个表型,可以作为表值参数:

CREATE TYPE FileNameType AS TABLE (FileName VARCHAR(255)); 

接下来,你需要定义以此表类型作为其参数并将来自TVP的数据插入表中的存储过程:

CREATE PROCEDURE dbo.InsertFileNames 
    @TVP FileNameType READONLY 
AS 
    SET NOCOUNT ON 

    INSERT INTO FileTest(FileName, DateInserted) 
     SELECT FileName, Sysdatetime() 
     FROM @TVP; 
现在

,在C#代码,你需要有这样的事情:

// define some strings we need - connection string, name of stored procedure, name of the table type 
string connectionString = "server=.;Database=test;Integrated Security=SSPI;"; 
string storedProcedureName = "dbo.InsertFileNames"; 
string tvpValueTypeName = "FileNameType"; 

// set up data to insert - create a DataTable that has the same structure as your TVP type in SQL Server 
DataTable filesNamesToAdd = new DataTable(); 
filesNamesToAdd.Columns.Add(new DataColumn("FileName", typeof (string))); 

// insert some rows into that DataTable 
DataRow row = filesNamesToAdd.NewRow(); 
row["FileName"] = "C:\\autoexec.cmd"; 
filesNamesToAdd.Rows.Add(row); 

row = filesNamesToAdd.NewRow(); 
row["FileName"] = "C:\\Windows\\Explorer.exe"; 
filesNamesToAdd.Rows.Add(row); 

row = filesNamesToAdd.NewRow(); 
row["FileName"] = "C:\\Windows\\starter.xml"; 
filesNamesToAdd.Rows.Add(row); 

row = filesNamesToAdd.NewRow(); 
row["FileName"] = "C:\\Windows\\WindowsUpdate.log"; 
filesNamesToAdd.Rows.Add(row); 

row = filesNamesToAdd.NewRow(); 
row["FileName"] = "C:\\Windows\\mip.bin"; 
filesNamesToAdd.Rows.Add(row); 

// set up SqlConnection and SqlCommand in using blocks 
using(SqlConnection conn = new SqlConnection(connectionString)) 
using (SqlCommand insertCommand = new SqlCommand(storedProcedureName, conn)) 
{ 
    // define the SqlCommand to be a stored procedure we're calling 
    insertCommand.CommandType=CommandType.StoredProcedure; 

    // define the table-valued parameter; it's of type SqlDbType.Structured, and you need to tell it the TVP type in SQL Server 
    SqlParameter tvpParam = insertCommand.Parameters.Add("@TVP", SqlDbType.Structured); 
    tvpParam.TypeName = tvpValueTypeName; 
    tvpParam.Value = filesNamesToAdd; 

    // open connection, call the stored procedure to insert data, close connection 
    conn.Open(); 
    insertCommand.ExecuteNonQuery(); 
    conn.Close(); 
} 

完成!