Writing an existing Excel file from db but with different headers - sql

I have a problem that i can't solve even if i looked everywhere for a solution. I got an excel that have to be written from a table in my db, problem is that the headers in my db are named different than the headers in my excel file and I need to keep them like that. Another problem is that the index of the columns are also diffrent...It would be great if i could make a query for each column and write the result to the excel file by indicating the column's index, something like that:
Dim column1 As String = "SELECT [columnName] from [tableName] "
and then
Sheets("SheetName").Columns("ColumnName").value = column1
obviously it doesn't work it's just to let you know my idea...

Build your SQL query to match the order of the excel file and then fill in your result like
for (int i = 0; i < table.Columns.Count; i++)
{
Sheets("SheetName").Columns(i).value = table.Columns[i].ColumnName
}
and add another for-loop for the rows on the table.Rows to fill in the values

Related

Test Excel cell value against SQL Server field

I have an Excel form that contains a project name that I want to make sure is unique when compared to values in a SQL table. I want to do this without importing the SQL table into the worksheet. I was thinking of something like this:
Dim uniqueProjectName as Int
Dim suggstedProjectName as String
suggestedProjectName = WorkSheets("Form").Range("ProjectName")
If (Select Count(pName) from PROJECTS.dbo.Projects WHERE pName = suggestedProjectName) = 0
Then uniqueProjectName = 1
Else uniqueProjectName = 0
Can anyone help with the syntax?
Thanks everyone, I was able to use an ADODB connection and everything works as designed now....

How to add to the end of text column through sql?

I am trying to create an sql query that adds a string to the end of the cell. Right now I have this.
$sql = "UPDATE table SET $column1= $column1 + $newstring1, $column2 = $column2 + $newstring2, $column3 = $column3 + $newstring3, WHERE username = $user_username";
The values of $newstring1, $newstring2, and $newstring3 are formatted like "155:2,"
The idea is to add delimiters to each entry so I can easily sort them later. Right now I'm getting a syntax error on my query, but I'm new to php. Is the error because when the database is empty, there is no original variable and therefore I need to INSERT INTO instead of UPDATE, or is the comma in the string itself creating the error and do I need to somehow concatenate it?
I'm more used to C# than PHP so I'm not sure the proper way to format that type of query.

Sorting Data on Form in Access 2010 by VBA

I have the following setup:
Table "Mitarbeiter" (Users) with fields: "UNummer" / "Sortierung" /....
Table "Mo01" (a sheet for every month) with fields: "UNummer" / "01" / "02" / ....
The Field UNummer in Table Mo01 is a combination field that gets Mitarbeiter.UNummer and saves it as text
I call a Form "Monatsblatt" that is based on the table Mo01.
In that Form I have a Field "fldSort" that is calling "Sortierung" from table "Mitarbeiter". The Data in that field is based on "=DomWert("Sortierung";"Mitarbeiter";"UNummer = '" & [ID] & "'")"
This works and looks like this:
I am trying to sort the form by that "fldSort" in Form "Monatsblatt" by using this code:
Form_Monatsblatt.OrderBy = "fldSort"
Form_Monatsblatt.OrderByOn = True
When I start the form with that code running, Access asks for parameters:
I tried a lot of different ways of writing the code, referencing to the field in different ways. I do NOT want to base the form on anything other then the table.
Why not ask the wide world watch "Why Access asking me for Parameter"? That would have brought you to the clue I think. Debug.Print or MsgBox your .OrderBy and you see it's "fldSort", not a valid sort. Access is assuming you want to use a parameter called fldSort, but you want the string in the variable fldSort, but it's not recognized, because of the double quotes surrounding it. Everything between 2 double quotes is interpreted as a string, even it's a var name.
Delete the quotes and everything will work fine (if your sort string is sufficent)!
Form_Monatsblatt.OrderBy = fldSort
[Update]
Late, but now I see the clue. You added a calculated field to the form, but you can't sort or filter them.
Instead of appending this field to the table, create a query and add it there, then you bind the form to the query and add the field to the form. Now you can filter and sort as you like!
The query looks like this:
SELECT *,
Dlookup("Sortierung","Mitarbeiter","UNummer = '" & [ID] & "'") AS ldSort
FROM Mo01;
Or with a join:
SELECT
Mo01.*,
Mitarbeiter.Sortierung AS fldSort
FROM
Mo01
LEFT JOIN
Mitarbeiter
ON
Mo01.ID = Mitarbeiter.UNummer;
Now you can use
Form_Monatsblatt.OrderBy = "fldSort"
Form_Monatsblatt.OrderByOn = True
because you have a bound control called fldSort.
[/Update]

Generate sql insert script from excel worksheet

I have a large excel worksheet that I want to add to my database.
Can I generate an SQL insert script from this excel worksheet?
I think importing using one of the methods mentioned is ideal if it truly is a large file, but you can use Excel to create insert statements:
="INSERT INTO table_name VALUES('"&A1&"','"&B1&"','"&C1&"')"
In MS SQL you can use:
SET NOCOUNT ON
To forego showing all the '1 row affected' comments. And if you are doing a lot of rows and it errors out, put a GO between statements every once in a while
You can create an appropriate table through management studio interface and insert data into the table like it's shown below. It may take some time depending on the amount of data, but it is very handy.
There is a handy tool which saves a lot of time at
http://tools.perceptus.ca/text-wiz.php?ops=7
You just have to feed in the table name, field names and the data - tab separated and hit Go!
You can use the following excel statement:
="INSERT INTO table_name(`"&$A$1&"`,`"&$B$1&"`,`"&$C$1&"`, `"&$D$1&"`) VALUES('"&SUBSTITUTE(A2, "'", "\'")&"','"&SUBSTITUTE(B2, "'", "\'")&"','"&SUBSTITUTE(C2, "'", "\'")&"', "&D2&");"
This improves upon Hart CO's answer as it takes into account column names and gets rid of compile errors due to quotes in the column. The final column is an example of a numeric value column, without quotes.
Depending on the database, you can export to CSV and then use an import method.
MySQL - http://dev.mysql.com/doc/refman/5.1/en/load-data.html
PostgreSQL - http://www.postgresql.org/docs/8.2/static/sql-copy.html
Use the ConvertFrom-ExcelToSQLInsert from the ImportExcel in the PowerShell Gallery
NAME
ConvertFrom-ExcelToSQLInsert
SYNTAX
ConvertFrom-ExcelToSQLInsert [-TableName] <Object> [-Path] <Object>
[[-WorkSheetname] <Object>] [[-HeaderRow] <int>]
[[-Header] <string[]>] [-NoHeader] [-DataOnly] [<CommonParameters>]
PARAMETERS
-DataOnly
-Header <string[]>
-HeaderRow <int>
-NoHeader
-Path <Object>
-TableName <Object>
-WorkSheetname <Object>
<CommonParameters>
This cmdlet supports the common parameters: Verbose, Debug,
ErrorAction, ErrorVariable, WarningAction, WarningVariable,
OutBuffer, PipelineVariable, and OutVariable. For more information, see
about_CommonParameters (http://go.microsoft.com/fwlink/?LinkID=113216).
ALIASES
None
REMARKS
None
EXAMPLE
ConvertFrom-ExcelToSQLInsert MyTable .\testSQLGen.xlsx
You could use VB to write something that will output to a file row by row adding in the appropriate sql statements around your data. I have done this before.
Here is another tool that works very well...
http://www.convertcsv.com/csv-to-sql.htm
It can take tab separated values and generate an INSERT script. Just copy and paste and in the options under step 2 check the box "First row is column names"
Then scroll down and under step 3, enter your table name in the box "Schema.Table or View Name:"
Pay attention to the delete and create table check boxes as well, and make sure you examine the generated script before running it.
This is the quickest and most reliable way I've found.
You can use the below C# Method to generate the insert scripts using Excel sheet just you need import OfficeOpenXml Package from NuGet Package Manager before executing the method.
public string GenerateSQLInsertScripts() {
var outputQuery = new StringBuilder();
var tableName = "Your Table Name";
if (file != null)
{
var filePath = #"D:\FileName.xsls";
using (OfficeOpenXml.ExcelPackage xlPackage = new OfficeOpenXml.ExcelPackage(new FileInfo(filePath)))
{
var myWorksheet = xlPackage.Workbook.Worksheets.First(); //select the first sheet here
var totalRows = myWorksheet.Dimension.End.Row;
var totalColumns = myWorksheet.Dimension.End.Column;
var columns = new StringBuilder(); //this is your columns
var columnRows = myWorksheet.Cells[1, 1, 1, totalColumns].Select(c => c.Value == null ? string.Empty : c.Value.ToString());
columns.Append("INSERT INTO["+ tableName +"] (");
foreach (var colrow in columnRows)
{
columns.Append("[");
columns.Append(colrow);
columns.Append("]");
columns.Append(",");
}
columns.Length--;
columns.Append(") VALUES (");
for (int rowNum = 2; rowNum <= totalRows; rowNum++) //selet starting row here
{
var dataRows = myWorksheet.Cells[rowNum, 1, rowNum, totalColumns].Select(c => c.Value == null ? string.Empty : c.Value.ToString());
var finalQuery = new StringBuilder();
finalQuery.Append(columns);
foreach (var dataRow in dataRows)
{
finalQuery.Append("'");
finalQuery.Append(dataRow);
finalQuery.Append("'");
finalQuery.Append(",");
}
finalQuery.Length--;
finalQuery.Append(");");
outputQuery.Append(finalQuery);
}
}
}
return outputQuery.ToString();}
Here is a link to an Online automator to convert CSV files to SQL Insert Into statements:
CSV-to-SQL
This query i have generated for inserting the Excel file data into database
In this id and price are numeric values and date field as well. This query summarized all the type which I require It may useful to you as well
="insert into product (product_id,name,date,price) values("&A1&",'" &B1& "','" &C1& "'," &D1& ");"
Id Name Date price
7 Product 7 2017-01-05 15:28:37 200
8 Product 8 2017-01-05 15:28:37 40
9 Product 9 2017-01-05 15:32:31 500
10 Product 10 2017-01-05 15:32:31 30
11 Product 11 2017-01-05 15:32:31 99
12 Product 12 2017-01-05 15:32:31 25
I had to make SQL scripts often and add them to source control and send them to DBA.
I used this ExcelIntoSQL App from windows store https://www.microsoft.com/store/apps/9NH0W51XXQRM
It creates complete script with "CREATE TABLE" and INSERTS.
I have a reliable way to generate SQL inserts batly,and you can modify partial parameters in processing.It helps me a lot in my work, for example, copy one hundreds data to database with incompatible structure and fields count.
IntellIJ DataGrip , the powerful tool i use.
DG can batly receive data from WPS office or MS Excel by column or line.
after copying, DG can export data as SQL inserts.

VBA While loop using an SQL statement as my While

I'm writing some code behind some spreadsheets and I need to loop through some code, like getting data from a database doing some formulas and moving the data to a new sheet. My code for getting the data from the database is getting all of the values in multiple columns where the data has not been reported and has the same file name ( the data is coming from a file ), I have a field which states whether or not it has be reported by a simple "Y" or "N", and a field which holds the filename it came from.
So I need a while that, "WHILE" there's data that hasn't been reported do the rest of my code ( this includes my first SQL statement I said as this get data that hasn't been reported from each individual filename ).
I've been trying to get this to work for days but just have not been able to figure out how, so any help would be very grateful.
Update:
Database has a entity called datareported, can either be "N" or "Y", and also datadatfile which is the name from which the data came from.
So,
WHILE datareported = 'N' THEN
"SELECT (the data rows I want)
FROM tbldata
WHERE datareported='N' and datadatfile =
(SELECT min(datadatfile)
FROM tbldata WHERE datareported='N')"
This means that I loop through the rest of my code WHILE there is data that hasn't been reported and only bring in data of the same name ( from datadatfile ) so that the code can be run on that data.
That's basically what I want to do and that's pretty much what I have tried. I have tried a few other things and normally get a return of type mis-match.
Cheers,
Sam
More information needed for a solution but this may be of some help to push you in the right direction...
'ws1 = worksheet object...
bC = true
cnt1 = 2 ' starting row
Do While bC
If ws1.cells(cnt1, 1) = "N" Then
'Run your SQL here
Else
'Already reported...
End If
cnt1 = cnt1 + 1
If 'you hit the last row on your worksheet set bC = False to exit loop
Loop
Missed the update...this wont help, sorry.