Passing multiple rows to SQL Server Stored Procedure - excel

I have a problem that I want to pass multiple rows of Excel file to a SQL Server stored procedure and I don't have any idea about it.
I have an Excel file to be imported, data needs to be inserted into three different tables. I have successfully imported data into one table as follows
string path = string.Concat((Server.MapPath("~/temp/"+FileUpload1.FileName)));
FileUpload1.PostedFile.SaveAs(path);
OleDbConnection oleCon = new OleDbConnection("Provider=Microsoft.Ace.OLEDB.12.0;Data Source=" + path + ";Extended Properties = Excel 12.0;");
OleDbCommand cmd = new OleDbCommand("select * from [Sheet1$]",oleCon);
OleDbDataAdapter dtap = new OleDbDataAdapter(cmd);
oleCon.Open();
DbDataReader rdr = cmd.ExecuteReader();
string con_str = #"Data source = .;Initial Catalog=practiceDB;Integrated security=True";
SqlBulkCopy bulkInsert = new SqlBulkCopy(con_str);
bulkInsert.DestinationTableName = "Excel_New";
bulkInsert.WriteToServer(rdr);
oleCon.Close();
Array.ForEach(Directory.GetFiles((Server.MapPath("~/temp/"))),File.Delete);
How to send rows to stored procedure rather than to any DestinationTable?

Rather than passing the rows as parameters, how about just reading from your table Excel_New the in the stored procedure?

Related

Unpivot file with power query results in file with more than 1 million records

Is there any chance to get a file splitted before the unpivoting process is completed? I have tried to do the opposite, that is to split the file and then unpivot it, but it requires too much time due to the fact I have to deal with more than 20 files and I can't be able to write a functioning Macro to do the job.
I have to materialise it because I have to load the files into another software that does not have the unpivoting function in it and I can't get direct access to their databases to run any queries.
There is a possible solution using VBA. In this approach you need to:
Load the Power Query table into Power Pivot Workbook Data Model
Fetch data from the Workbook Data Model using VBA
Write the records into a CSV file
Below is step by step how to.
For proofing, I created a dummy table of 3 million rows inside Power Query using below code, naming it "MyData".
// MyData: A table of 3 million rows
let RowCount = 3000000
in Table.FirstN(
Table.FromColumns({
List.Generate(() => 1, each true, each _ + 1),
List.Generate(() => Number.Random() * 1000, each true, each Number.Random() * 1000)
}, type table [ID = Int64.Type, RandomNumber = number]),
RowCount
)
I loaded this table into the Workbook Data Model by selecting Close & Load To, then selecting Only Create Connection and checking Add this data to the Data Model.
Then, using below VBA code, I was able to connect to the Data Model, fetch the records, and dump it to a CSV file.
Const OutFile As String = "C:/path/to/MyData.csv"
Dim Wb As Workbook
Set Wb = Application.ActiveWorkbook
Wb.Model.Initialize
'Connection to the Data Model
Dim Conn As Object 'ADODB.Connection
Set Conn = Wb.Model.DataModelConnection.ModelConnection.ADOConnection
Dim Recordset As Object 'ADODB.Recordset
Set Recordset = CreateObject("ADODB.Recordset")
Dim Query As String
Query = "EVALUATE MyData" 'DAX query to return the entire table
Recordset.Open Query, Conn
Dim FileNum: FileNum = FreeFile()
Open OutFile For Output As #FileNum
Do While Not Recordset.EOF
Write #FileNum, Recordset("MyData[ID]"), Recordset("MyData[RandomNumber]")
Recordset.MoveNext
Loop
Close #FileNum

How to get table names from Presto query using presto-parser?

Not able to extract table names used within with clause, I'm using presto-parser version 0.226.
SqlParser sqlParser = new SqlParser();
String sql = "WITH dataset AS ( SELECT ROW('Bob', 38) AS users from tabb ) SELECT * FROM dataset";
Query query = (Query)sqlParser.createStatement(sql, ParsingOptions.builder().build());
QuerySpecification body = (QuerySpecification)query.getQueryBody();
System.out.println("From = " + body.getFrom().get());
/* Output
From = Table{dataset}
*/
Expected output
From = Table{dataset, tabb}

Counting no. of filled rows in Access Db

I am using the following code for fetching the no. of filled rows in MS Access Db. But I am getting the following error at open command
public static int CountRecordsInAccess(string ResultFile)//TODO
{
string ResultFilePath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + ResultFile;
string ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0" + ";Data Source=" + ResultFilePath + ";Extended Properties=Excel 12.0;Persist Security Info=False";
//Create Connection
OleDbConnection AccessConnection = new OleDbConnection(ConnectionString);
AccessConnection.Open();
//Create OleDbCommand to fetch data
OleDbCommand cmd = new OleDbCommand("SELECT COUNT (*) FROM Table1" , AccessConnection);
int rows = (int)cmd.ExecuteScalar();
AccessConnection.Close();
return rows;
}
Please suggest where I am going wrong
string ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0" + ";Data Source=" + ResultFilePath + ";Persist Security Info=False";

How to select All the Tables in Access DataBase 2007 using query

I am working in C#.net.I want to select all table names in the Access Database using Query. Can any one tell... How to select all the tables name from access database using query?.
Try like below it will help you...
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\myAccess2007file.accdb;Persist Security Info=False;";
OleDbConnection conn = new OleDbConnection(connectionString);
conn.Open();
DataTable tables = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,new object[]{null,null,null,"TABLE"});
conn.Close();
Now the Datatable "tables" have all the access table Info..

Is there a fast way to get the number of rows in an Excel sheet using ADO.Net?

Is there a better way than
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=<xlxsName>;Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1;ReadOnly=True\"";
string sql = string.Format("SELECT COUNT (*) FROM [{0}] ", worksheetName);
using (OleDbConnection conn = new OleDbConnection(connectionString)) {
OleDbCommand cmd = new OleDbCommand(sql, conn);
conn.Open();
totalCount = (int)cmd.ExecuteScalar();
conn.Close();
}
to get a row count from an excel sheet? If possible I'd prefer to use ADO.Net instead of Excel interop

Resources