Import Excel spreadsheet columns into SQL Server database - sql-server

I have an Excel spreadsheet that I want to import select columns into my SQL Server 2008 database table. The wizard didn't offer that option.
Do any easy code options exist?

Once connected to Sql Server 2005 Database, From Object Explorer Window, right click on the database which you want to import table into. Select Tasks -> Import Data.
This is a simple tool and allows you to 'map' the incoming data into appropriate table.
You can save the scripts to run again when needed.

Microsoft suggest several methods:
SQL Server Data Transformation Services (DTS)
Microsoft SQL Server 2005 Integration Services (SSIS)
SQL Server linked servers
SQL Server distributed queries
ActiveX Data Objects (ADO) and the Microsoft OLE DB Provider for SQL Server
ADO and the Microsoft OLE DB Provider for Jet 4.0
If the wizard (DTS) isn't working (and I think it should) you could try something like this http://www.devasp.net/net/articles/display/771.html which basically suggests doing something like
INSERT INTO [tblTemp] ([Column1], [Column2], [Column3], [Column4])
SELECT A.[Column1], A.[Column2], A.[Column3], A.[Column4]
FROM OPENROWSET
('Microsoft.Jet.OLEDB.4.0', 'Excel 8.0;Database=D:\Excel.xls;HDR=YES', 'select * from [Sheet1$]') AS A;

This may sound like the long way around, but you may want to look at using Excel to generate INSERT SQL code that you can past into Query Analyzer to create your table.
Works well if you cant use the wizards because the excel file isn't on the server

You could use OPENROWSET, something like:
SELECT * FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;IMEX=1;HDR=NO;DATABASE=C:\FILE.xls', 'Select * from [Sheet1$]'
Just make sure the path is a path on the server, not your local machine.

go
sp_configure 'show advanced options',1
reconfigure with override
go
sp_configure 'Ad Hoc Distributed Queries',1
reconfigure with override
go
SELECT * into temptable
FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=C:\Documents and Settings\abhisharma\Desktop\exl\ImportExcel2SQLServer\ImportExcel2SQLServer\example.xls;IMEX=1',
'SELECT * FROM [Sheet1$]')
select * from temptable

Another option is to use VBA in Excel, and write a macro to parse the spreadsheet data and write it into SQL.
One example is here: http://www.ozgrid.com/forum/showthread.php?t=26621&page=1
Sub InsertARecord()
Dim cnt As ADODB.Connection
Dim rst As ADODB.Recordset
Dim stCon As String, stSQL As String
Set cnt = New ADODB.Connection
Set rst = New ADODB.Recordset
stCon = "Provider=MSDASQL.1;Persist Security Info=False;Data Source=JOEY"
cnt.ConnectionString = stCon
stSQL = "INSERT INTO MyTable (Price)"
stSQL = stSQL & "VALUES (500)"
cnt.Open
rst.Open stSQL, cnt, adOpenStatic, adLockReadOnly, adCmdText
If CBool(rst.State And adStateOpen) = True Then rst.Close
Set rst = Nothing
If CBool(cnt.State And adStateOpen) = True Then cnt.Close
Set cnt = Nothing
End Sub

By 'the wiz' I'm assuming you're talking about the 'SQL Server Import and Export Wizard'. (I'm also pretty new so I don't understand most questions, much less most answers, but I think I get this one). If so couldn't you take the spreadsheet, or a copy of it, delete the columns you don't want imported and then use the wizard?
I've always found the ability to do what I need with it and I'm only on SQL Server 2000 (not sure how other versions differ).
Edit: In fact I'm looking at it now and I seem to be able to choose which columns I want to map to which rows in an existing table. On the 'Select Source Tables and Views' screen I check the datasheet I'm using, select the 'Destination' then click the 'Edit...' button. From there you can choose the Excel column and the table column to map it to.

If you would like a visual tool with Desktop interface including validation .. you may well like this Excel tool. You can also use the tool to create multi user data-edit tasks, or even paste data to SQL server from any source..
How to Validate and Import Excel spreadsheet to SQL Server database:
http://leansoftware.net/en-us/help/excel-database-tasks/worked-examples/how-to-import-excel-spreadsheet-to-sql-server-data.aspx

Microsoft Access is another option. You could have a Access database locally on your machine that you import the excel spreadsheets into (wizards available) and link to the the SQL Server database tables via ODBC.
You could then design a query in access that appends data from the Excel spreadsheet to the SQL Server Tables.

The best tool i've ever used is http://tools.perceptus.ca/text-wiz.php?ops=7 Did you try it?

I think it will help you
Visit http://social.msdn.microsoft.com/Forums/en-US/sqlgetstarted/thread/78f8e980-0bb6-4a48-b1b1-5f65bca1d511

The import wizard does offer that option. You can either use the option to write your own query for the data to import, or you can use the copy data option and use the "Edit Mappings" button to ignore columns you do not want to import.

Excel + SQLCMD + Perl = exceltomssqlinsert
and you can use your Excel as frond-end to MSSQL db ... Note the truncate table at the beginning of each generated sql insert file ...

I have used DTS (now known as SQL server Import and Export Wizard). I used the this tutorial which worked great for me even in Sql 2008 and excel 2010 (14.0)
I hope this helps
-D

First of all, try the 32 Bit Version of the Import Wizard. This shows a lot more supported import formats.
Background:
All depends on your Office (Runtimes Engines) installation.
If you dont't have Office 2007 or greater installed, the Import Wizard (32 Bit) only allows you to import Excel 97-2003 (.xls) files.
If you have the Office 2010 and geater (comes also in 64 Bit, not recommended) installed, the Import Wizard also supports Excel 2007+ (.xlsx) files.
To get an overview on the runtimes see 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine

Related

Export from Access .mdb database with ODBC link to SQL Server into Access format database using VBA

I have an Access 2019 front-end database that links to a SQL Server 2017 Express database.
I'd like to export a table or query from the VBA code in the front-end into an Access (Jet) format database (as a portable data format to use for updating a remote site)
The code I've tried (for a table called FileLocation) is:
Access.DBEngine.CreateDatabase "C:\Temp\ExportTest3.mdb", DB_LANG_GENERAL
docmd.TransferDatabase transfertype:=acExport, databasetype:="Microsoft Access",databasename:="c:\temp\ExportTest3.mdb", objecttype:=acTable, source:="FileLocation", destination:="FileLocation", structureonly:=false
This "works" but the table created in the ExportTest3 database is a link to the SQL database (with the Connect property set in MSysObjects) so is dependant on the SQL Server connection, but I'm looking for an independant portable .mdb file that can be read on any PC.
Edit: I've discovered that I can use
docmd.RunSQL "select * into FileLocationLocal from FileLocation"
and then use TransferDatabase to export the FileLocationLocal table as a non-linked table
But is there a way to do this as a single step, or is there a better approach?
Consider:
Access.DBEngine.CreateDatabase "C:\Temp\ExportTest3.mdb", DB_LANG_GENERAL
CurrentDb.Execute "SELECT FileLocation.* INTO FileLocation IN 'C:\Temp\ExportTest3.mdb' FROM FileLocation"

Export SQL query to excel with multiple worksheets and custom headers

What I need to do is, a client wants to have a report in an excel doc with multiple worksheets with custom headers. I have tried SSRS 2008 Report Builder 2.0 but naming worksheets is not available with SSRS 2008 Report Builder 2.0. I have tried bcp in SQL Server Management Studio, but am not able to export it into multiple worksheets. I have put the queries into temp tables, is there a way to export those queries into the same excel doc but different worksheets with a different header for each worksheet.
Like this
Notice how each worksheet has a different name and a different header.
Is this possible to do with SQL or is there a workaround for SSRS 2008 Report Builder 2.0?
You could use SQL Server Integration Services 2008R2 (SSIS) to do this. SSIS has an Excel Data Flow Destination that accepts a worksheet name as a parameter. You could construct your SSIS package to populate the various worksheets of a spreadsheet this way.
I know, I know... you too you faced the error:
Msg 15281, Level 16, State 1, Line 1
SQL Server blocked access to STATEMENT ‘OpenRowset/OpenDatasource’ of component ‘Ad Hoc Distributed Queries’ because this component is turned off as part of the security configuration for this server. A system administrator can enable the use of ‘Ad Hoc Distributed Queries’ by using sp_configure. For more information about enabling ‘Ad Hoc Distributed Queries’, search for ‘Ad Hoc Distributed Queries’ in SQL Server Books Online.
You can do it in SSMS through T-SQL, follow this example:
First you need to allow SSMS to bypass the error:
EXEC sp_configure 'show advanced options', 1
RECONFIGURE
EXEC sp_configure 'Ad Hoc Distributed Queries', 1
RECONFIGURE
Then you can save the result in a precise Excel Tab this way:
INSERT INTO OPENROWSET('Microsoft.ACE.OLEDB.12.0','Excel 12.0;
Database=C:\Users\Zivko\Desktop\SQL Data.xlsx;','SELECT * FROM [Sheet1$]')
SELECT * FROM dbo.DimScenario
The file .XLSX must already be there with the tab having the precise name [Sheet1$]

Can DAO access schemas in current Sql Server versions?

We have an app we maintain which is written in VB6 and uses the prehistoric DAO technology to do its database access. The database is in Sql Server 2008.
We are writing a new module now, that I wanted to logically separate off with its own schema. However when I try to write a simple select query like:
SELECT ROWID, NAME FROM exports.TYPES ORDER BY NAME
DAO is complaining:
Error # 3024
Couldn't find file 'C:\Program Files\Microsoft Visual Studio\VB98\exports.mdb'.
So clearly, DAO is interpreting the schema as a different database... is there any way to tell it to just pass the query through to the Sql Server?
This app is NOT using Access at all, just the DAO libraries.
Grrr... after googling for a half-an-hour, and then finally deciding to post a Q, then I try one more google and find the answer. Sheesh! I hate when that happens!
Anyway, here is the answer for those who may need it in the future.
I had to change my OpenRecordset statement from this:
Set rs = db.OpenRecordset(SQL, dbOpenSnapshot, dbSeeChanges)
to this:
Set rs = db.OpenRecordset(SQL, dbOpenSnapshot, dbSeeChanges Or dbSQLPassThrough)
Answer is from this KB on ms.com.

Help with MS Access and SQL Server 2008

I need somebody to point me to the right direction, I have a MS Access DB that is updated by HP devices, and I have to sync it with the SQL Server 2008.
I have a few Ideas, and I would like to know what do you think about this:
Is there anything like triggers on access? if so can I comunicate with a SQL Server?
Is there any way to use VBA so access tell my VBA macro or whatever to make an update on SQL Server?
Is there a simple way to connect from VB 6 to SQL Server 2008?
Using a script that run at background and check DB at X minutes or seconds.
Any other ideas or suggestions are very welcome.
Thanks and like always sorry for the english.
Just to add a few points to adopilot’s answer
1) Access 2010 does have triggers and stored procedures but they are more about native access/jet tables as opposed to linked SQL tables I believe.
2 & 3) If you want to connect VB6 or VBA to an SQL server then the technology to do that is called ADO for example here is some code to open a connection and run a SQL statement
Dim dbCon as NEW ADODB.Connection
dbCon.ConnectionString = strSQL_con_string
dbCon.Provider = "sqloledb"
dbCon.Open
dbCon.Execute “UPDATE tblFoo SET bar=5 WHERE Foo=1”
dbCon.Close
4) You can either do this client side with a timer/wait event in VB6/Access or do it server side with a SQL job, not sure which is best for your situation given the limited information provided
You can refer to either the SQL Server database or the MS Access database inline in your SQL:
UPDATE SQLTable (ID, Stuff)
SELECT ID, Stuff
FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'c:\External\MyAccess.mdb';'admin';'', Table1)
-- From databasejournal
You can execute this query using ADO with a connection to SQL Server
-- Connection strings
You can also do the same from the Access end with ODBC
Dim cn As New ADODB.Connection
scn = "Provider=Microsoft.Jet.OLEDB.4.0;User ID=Admin;Data Source=" _
& DBFullName
cn.Open scn
s = "INSERT INTO [ODBC;Description=TEST;DRIVER=SQL Server;" _
& "SERVER=Server\Instance;Trusted_Connection=Yes;" _
& "DATABASE=test].Table2 (ID, Stuff) SELECT ID, Stuff FROM Table1"
cn.Execute s
You can run ADO with VBScript, or other suitable script and use Windows Task Scheduler to kick the script off at suitable intervals. This is not without pain.
You can try to link MS Access database to SQL server,
Now you can querying data from SQL server which is in MS Access.
I do not know about trigers on MS ACCESS but you can implement some loops in
MS SQL to periodicity count or select data for cheking new one.
To make linked server in SQL MGM Studio on Object Explorer -> Server Object -> Linked server -> right click -> New linked server
After then in new query simple call any table like
Select * from [linked server].dbo.mytable
In MS SQL there is WAITFOR command which You can implement

Updating access 2000 database through code in VB6

I have an application that uses an access 2000 database currently in distribution.
I need to update one of the recordsets with additional fields on my customer's computers.
My data controls work fine as I have them set to connect in access 2000 format. But, when I try to open the database in code, I get an unrecognized data format error.
What is the best way to replace or add to the database on their machines?
It is possible to update an Access database using VBScript, ADO and DDL.
strCon="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Example.mdb;" _
& "Jet OLEDB:Database Password=pass;"
Set cn=CreateObject("ADODB.Connection")
cn.Open strCon
strSQL="ALTER TABLE Example ADD COLUMN Example Text (20)"
cn.Execute strSQL
More connections strings: www.connectionstrings.com
I much prefer using DAO collections to updating BE database schemas as it gives you much more control over what you can do. For example you can easily delete or create tables, records, indexes and relationships. See the TempTables.MDB page at my website which illustrates how to use a temporary MDB in your app and has sample code to get you started.

Resources