Below is my stored procedure and my C# code. Currently, my rows count is 1000+ but I when I do tvp.Rows.Count I get 90 I believe my for loop is not really populating everything correctly. Here is my code snippet below. Mind you that the datatable is not populating my table in SQL Server.
Stored procedure:
ALTER PROCEDURE [dbo].[TableName]
@dt AS dbo.DataTableAsType READONLY
AS
BEGIN
INSERT INTO dbo.[DataTableAsType] ([Column names]) --There are 89 column names
SELECT
([ColumnNames])
FROM
@dt
END
Second stored procedure:
@totalRecords INT OUTPUT
INSERT INTO dbo.tablename1
FROM dbo.tablename2
SELECT @totalRecords = COUNT(*)
FROM dbo.[tableName2]
C# code:
public void InsertDataTableAF2CSV(string ext)
{
DataTable tvp = new DataTable();
tvp = ReadFile(filename, "", null);
using (StreamReader sr = new StreamReader(filename))
{
//this assume the first record is filled with the column names
//if (headerRowHasBeenSkipped)
string headerValue = sr.ReadLine();
string[] headers = sr.ReadLine().Split(',');
foreach (string header in headers)
{
tvp.Columns.Add(header);
}
while (!sr.EndOfStream)
{
string[] rows = sr.ReadLine().Split(',');
//Create a new row
DataRow dr = tvp.NewRow();
for (int i = 0; i < headers.Length; i++)
{
dr[i] = rows[i];
}
tvp.Rows.Add(dr);
// Console.WriteLine(tvp);
}
}
// Passing a table-valued parameter to a stored procedure
using (SqlConnection con = new SqlConnection(connection name))
{
connection.Open();
// Execute the cmd
// Configure the command and parameter.
SqlCommand cmd = new SqlCommand("dbo.storedprocedure", connection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandTimeout = 5000;
// SqlParameter tvparam = cmd.Parameters.AddWithValue("@dt", tvp);
// Create a DataTable with the modified rows.
DataTable addedCategories = tvp.GetChanges(DataRowState.Added);
// these next lines are important to map the C# DataTable object to the correct SQL User Defined Type
SqlParameter parameter = new SqlParameter("@dt", SqlDbType.Structured)
{
//TypeName = "dbo.DataTableAsType",
TypeName = "dbo.importDataTable",
Value = tvp
};
cmd.ExecuteNonQuery();
con.Close();
}
}