OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)" returned message "Syntax error in JOIN operation." - sql

I am getting this annoying error, but the thing is that I do not use any JOIN operation in my query. Here is the snippet:
('Microsoft.ACE.OLEDB.12.0','Excel 12.0;Database=C:\Users\tcmnoc\Desktop\Test.xlsx;','SELECT * FROM ([TradeCloud].[dbo].[Adminlist]')
Select * from [TradeCloud].[dbo].[Adminlist]```

Assuming your snippet derives from an OPENROWSET query, you are conflating data sources where you attempt to reference an SQL Server table inside an Excel connection. When connecting to an Excel workbook as a data source, you can only reference Excel worksheets, not SQL Server tables.
Therefore, this source is not recognizable: [TradeCloud].[dbo].[Adminlist] (correcting the opening parenthesis with square bracket). Instead, connect to an actual Excel worksheet within the workbook connection, placing the named reference outside of the connection string. Below query (after you adjust mySheet should work to retrieve Excel-only data):
SELECT *
FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0',
'Excel 12.0; Database=C:\Users\tcmnoc\Desktop\Test.xlsx;',
[mySheet])
Without fuller context, I consider the following assumptions:
Maybe Excel is connected to the [TradeCloud].[dbo].[Adminlist] table? If so, you need to make a separate, direct connection to the database and schema to access the table (bypassing Excel which is just another client connection).
Maybe you meant to populate an existing SQL Server table? If so, run the needed append or create-table command then browse its contents:
-- APPEND TO TABLE
INSERT INTO [TradeCloud].[dbo].[Adminlist] (Col1, Col2, Col3, ...)
SELECT xl.Col1, xl.Col2, xl.Col3, ...
FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0',
'Excel 12.0; Database=C:\Users\tcmnoc\Desktop\Test.xlsx;',
[mySheet]) xl;
-- CREATE TABLE
SELECT xl.Col1, xl.Col2, xl.Col3, ...
INTO [TradeCloud].[dbo].[Adminlist]
FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0',
'Excel 12.0; Database=C:\Users\tcmnoc\Desktop\Test.xlsx;',
[mySheet]) xl;
-- BROWSE CONTENTS
SELECT * [TradeCloud].[dbo].[Adminlist];
Maybe you are attempting to populate an Excel workbook? If so, do note, these commands (OPENROWSET and OPENDATASOURCE) do not populate an existing Excel workbook but simply connects to external sources (Excel, Access, or other data sources) as a backend to retrieve data.

Related

Import Excel Data Into Temporary Table Without Using OLEDB in SQL Server

I am trying to look for a way to import excel data into a temporary table without using OLEDB since I don't have OLEDB installed in SQL Server and I can not install it due to security restrictions.
I am aware of below mentioned ways of doing it but this is not going to help me
Begin Tran
If OBJECT_ID('tempdb..#tblUserImport') IS NOT NULL
Begin
Drop table #tblUserImport
end
Create Table [dbo].[#tblUserImport]
(
id nvarchar(max) NULL,
Name nvarchar(max) NULL,
Job_Title nvarchar(max) NULL,
Work_Email nvarchar(max) NULL
)
INSERT INTO [dbo].[#tblUserImport]
SELECT id, Name, Job Title, Work Email
FROM
OPENROWSET('Microsoft.ACE.OLEDB.12.0','Excel12.0;HDR=YES;Database=C:\Users\Desktop\Book2.xlsx', 'SELECT * FROM [Sheet1$]');
select * from [#tblUserImport]
Rollback Tran
I will get the below mentioned error if I execute the openrowset.
The OLE DB provider "Microsoft.ACE.OLEDB.12.0" has not been registered.
Is it possible to achieve it using Stored Procedure or any other way?
Here are 3 options:
1.Do the import from a computer you have admin rights on
It sounds like you don't have the ability to install OLE or ODBC data providers on the SQL Server machine. But you don't have to run the import from the same machine. As long as you have valid credentials and a working network path to your SQL server, you can run the import from any computer. So you could install the Microsoft ACE OLEDB 12.0 data provider driver on another PC along with SQL Server Management Studio, copy the Excel file there, and then do the import through the wizard.
Try an alternate data provider driver
There are alternate data provider drivers for Excel sources that may already be installed in your environment. E.g. the Jet OLEDB 4.0 driver mentioned at https://www.connectionstrings.com/excel/. Connection string:
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\MyExcel.xls;
Extended Properties="Excel 8.0;HDR=Yes;IMEX=1";
Use Excel formulas to build INSERT statements
You can use the venerable Excel formula trick alluded to in RBell's answer: Assuming the fields you specified in your question are in A1 through D1, add this formula to cell E1:
="INSERT INTO #tblUserImport VALUES ('"&SUBSTITUTE(A1, "'", "''")&"', '"&SUBSTITUTE(B1, "'", "''")&"', '"&SUBSTITUTE(C1, "'", "''")&"', '"&SUBSTITUTE(D1, "'", "''")&"');"
You then copy this formula down through all rows of your data. Excel will automatically alter the cell references for each row. Note that the SUBSTITUTE() function handles single-quotes in the data that might otherwise break the SQL syntax. Then you simply copy and paste the resulting text out into your SQL window, and run it.
super mcguyver way using table variables. use the concat function on your excel sheet to prepare the data for the insert part.
declare #temp1 table (id int identity(1,1),name varchar(255),job_title varchar(255),work_title varchar(255),work_email varchar(255));
insert into #temp1 (name,job_title,work_title,work_email)
values
('John','Electrician','level 3 lightning wizard','john#ex.com'),
('amy','Java Developer','Cyber Coffee Slinger','amy#ex.com');
Its quite a bit of work , but feasible
I am assuming you have read-only access to prod db with temp table creation and insert into temp table statements.
No access to sql wizards or any elevated privileges.
Below 4 steps we have to preform in our dev sql box. Then generate the create #temptable script and auto generated insert statements and run them in production temp database
save the excel as csv file to dev machine
create a #temptable/ ##temptable ( because usually developers wont have create table permissions in production database )
Note : if the table has more columns use wizard to generate the auto crate table statement.
How ?
Answer is : Right click on Database --> Task --> Import Data --> on sql server import and export wizard, select the data source as flat file source and browse the csv file what you created in step1. --> Next --> on the choose a destination select destination as sql server native client 11.0 --> next --> on select source table and views screen choose edit mappings --> on column mappings screen click edit sql button which gives auto generated create table statement.
Copy the auto generated script --> edit the name to ##TempTable_CSV --> Create the temp table.
Now table is ready. For data ,
Use Bulk insert by giving the csv path
BULK INSERT ##TempTable_CSV
FROM 'C:\Users<username>\Downloads\temp.csv'
WITH ( FIRSTROW = 2, FORMAT = 'CSV');
To auto generate the insert statements from the temp table ( for example assuming the temp table has id , varchar columns )
select 'insert ##TempTable_CSV values ('+Cast(Id as varchar(5))+','''+SomeVarcharColumn+''') from ##TempTable_CSV
which will generate all the insert into statements
Note : Make sure to handle null values
Finally you can copy the create temp table script from step 2 + auto generated insert statements from step 4 , run it in prod temp db.
Enjoy :-)

Run query connected to another database in VBA Access

I am trying to run saved query inside VBA Access. That query is connected to another database and looks like that:
SELECT * FROM TABLE IN 'C:\USERS\Another_database.accdb'
This query is saved as "My_query" inside first Access database. VBA code looks like this:
Function My_function()
Set rst = CurrentDb.OpenRecordset("My_query", dbOpenDynaset)
End Function
When I try to run it i got an error:
Run-time error '3219'
Any ideas why? It works for normal queries (without IN 'C:\USERS\Another_database.accdb' part.
The most efficient way to get data from another Access database on an ongoing basis is with Linked Tables.
Click External Data on the ribbon, then New Data Source → From Database → Access
Browse to the source database, and make sure you choose Link to the data source by creating a linked table
Select one or more tables that you want to link
[
The linked tables will be created and you will be able to query the linked tables as if they were local to the current database.
More Information:
Office Support : Import or link to data in another Access database
Office Support: Manage Linked Tables
Maybe you need to define a Recordset first or try to remove the quotation marks you have in the example? The following example works fine:
Dim rs as Recordset
Set rs = CurrentDb.OpenRecordset("SELECT Field FROM Table IN 'here goes your path'")
Now you have an Array rs() in which you can loop.

How to query data in Excel from Visual Studio 2013?

Background:
I am transferring data from one Excel document doc0 to a templated Excel document doc1 to speed up processes at work. My only real restriction is that I cannot modify the document's formatting, so regular VBA is not an option. I can only pull data out of doc0 modify it and place it in doc1. I am using Visual Studio 2013 for doing so.
What I need to do is:
Organize doc0 numerically by Col 1 first, then Col 3 second. Then place the top 10 results in a specific cell range in doc1.
Get a count for jobs assigned to each worker and return that result to Visual Studio. Worker names are listed in Col 4.
I know how to query using SQL, but am open to using other functions/languages that can perform the same task.
Question:
How can I query the data to perform the actions above?
A simple example can be seen with the link below. The blue represents doc0, the red the results to be displayed in doc1 and the green is the results that I need to have returned to corresponding textboxes in Visual Studio.
There are a few options. ADO.NET is able to connect to your excel sheet using OleDB to read data with simple query capability. Examples can be found in KB316934.
Connect to an Excel file to read and write data:
Connection String
To access an Excel workbook by using the Jet OLE DB Provider, use a connection string that has the following syntax:
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Book1.xls;Extended Properties="Excel 8.0;HDR=YES;"
Depending on your excel version, the connection string may slightly differ. Look them up here. E.g. 2013 would look like:
Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\myFolder\myExcel2007file.xlsx;
Extended Properties="Excel 12.0 Xml;HDR=YES";
Read and write data
Use the sheet name followed by a dollar sign (for example, [Sheet1$] or [My Worksheet$]). A workbook table that is referenced in this manner includes the whole used range of the worksheet.
select * from [Sheet1$]
Use a range with a defined name (for example, [MyNamedRange]):
Select * from [MyNamedRange]
Use a range with a specific address (for example, [Sheet1$A1:B10]):
Select * from [Sheet1$A1:B10]
Writing is done in a similar matter if you're using OleDB
INSERT INTO [Sheet1$] (F1, F2) values ('111', 'ABC')
UPDATE [Sheet1$] SET F2 = 'XYZ' WHERE F1 = '111'
You may need to create a temporary copy from which you can query data, as you may be reading and writing to the documents using different techniques.
Full example at the link (unfortunately in VB.NET).
Alternative solutions
If you really want full fidelity access to the Excel file, without depending on Excel being present or running, you could also investigate:
Excel Package Plus
NPIO
Aspose Cells.NET (commercial)
These packages do not support querying, so you'll need to extract the data into objects and use Linq-to-Objects to query/sort the data before writing it back to the files.

Excel Import Data via SQL Query

I would need to import the data from SQL Server using SQL query to get the data. I do this via Connection from Microsoft Query. The problem is, the data can be only imported as Table or Pivot Table. I need to import the data which are not formatted as table (due running VBA macro which does not work on data that are in table format).
Is there any option to import the data this way, just pure content?
This is the one I'm using since long
You can give it a try,
select *, ID
from
OPENROWSET('MICROSOFT.ACE.OLEDB.12.0', 'Excel 12.0;HDR=YES;DATABASE=C:\MyData.xlsx', sheet1$) where ID IS NULL

How do you transfer or export SQL Server 2005 data to Excel

I have a simple SQL 'Select' query, and I'd like to dump the results into an Excel file. I'm only able to save as .csv and converting to .xls creates some super ugly output. In any case, as far as I can tell (using Google) this doesn't seem to be so straight forward. Any help would be greatly appreciated.
SSIS is a no-brainer for doing stuff like this and is very straight forward (and this is just the kind of thing it is for).
Right-click the database in SQL Management Studio
Go to Tasks and then Export data, you'll then see an easy to use wizard.
Your database will be the source, you can enter your SQL query
Choose Excel as the target
Run it at end of wizard
If you wanted, you could save the SSIS package as well (there's an option at the end of the wizard) so that you can do it on a schedule or something (and even open and modify to add more functionality if needed).
Use "External data" from Excel. It can use ODBC connection to fetch data from external source: Data/Get External Data/New Database Query
That way, even if the data in the database changes, you can easily refresh.
I've found an easy way to export query results from SQL Server Management Studio 2005 to Excel.
1) Select menu item Query -> Query Options.
2) Set check box in Results -> Grid -> Include column headers when copying or saving the results.
After that, when you Select All and Copy the query results, you can paste them to Excel, and the column headers will be present.
See this
This is by far the best post for exporting to excel from SQL:
http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=49926
To quote from user madhivanan,
Apart from using DTS and Export wizard, we can also use this query to export data from SQL Server2000 to Excel
Create an Excel file named testing having the headers same as that of table columns and use these queries
1 Export data to existing EXCEL file from SQL Server table
insert into OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=D:\testing.xls;',
'SELECT * FROM [SheetName$]') select * from SQLServerTable
2 Export data from Excel to new SQL Server table
select *
into SQLServerTable FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=D:\testing.xls;HDR=YES',
'SELECT * FROM [Sheet1$]')
3 Export data from Excel to existing SQL Server table
Insert into SQLServerTable Select * FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=D:\testing.xls;HDR=YES',
'SELECT * FROM [SheetName$]')
4 If you dont want to create an EXCEL file in advance and want to export data to it, use
EXEC sp_makewebtask
#outputfile = 'd:\testing.xls',
#query = 'Select * from Database_name..SQLServerTable',
#colheaders =1,
#FixedFont=0,#lastupdated=0,#resultstitle='Testing details'
(Now you can find the file with data in tabular format)
5 To export data to new EXCEL file with heading(column names), create the following procedure
create procedure proc_generate_excel_with_columns
(
#db_name varchar(100),
#table_name varchar(100),
#file_name varchar(100)
)
as
--Generate column names as a recordset
declare #columns varchar(8000), #sql varchar(8000), #data_file varchar(100)
select
#columns=coalesce(#columns+',','')+column_name+' as '+column_name
from
information_schema.columns
where
table_name=#table_name
select #columns=''''''+replace(replace(#columns,' as ',''''' as '),',',',''''')
--Create a dummy file to have actual data
select #data_file=substring(#file_name,1,len(#file_name)-charindex('\',reverse(#file_name)))+'\data_file.xls'
--Generate column names in the passed EXCEL file
set #sql='exec master..xp_cmdshell ''bcp " select * from (select '+#columns+') as t" queryout "'+#file_name+'" -c'''
exec(#sql)
--Generate data in the dummy file
set #sql='exec master..xp_cmdshell ''bcp "select * from '+#db_name+'..'+#table_name+'" queryout "'+#data_file+'" -c'''
exec(#sql)
--Copy dummy file to passed EXCEL file
set #sql= 'exec master..xp_cmdshell ''type '+#data_file+' >> "'+#file_name+'"'''
exec(#sql)
--Delete dummy file
set #sql= 'exec master..xp_cmdshell ''del '+#data_file+''''
exec(#sql)
After creating the procedure, execute it by supplying database name, table name and file path:
EXEC proc_generate_excel_with_columns 'your dbname', 'your table name','your file path'
Its a whomping 29 pages but that is because others show various other ways as well as people asking questions just like this one on how to do it.
Follow that thread entirely and look at the various questions people have asked and how they are solved. I picked up quite a bit of knowledge just skimming it and have used portions of it to get expected results.
To update single cells
A member also there Peter Larson posts the following:
I think one thing is missing here. It is great to be able to Export and Import to Excel files, but how about updating single cells? Or a range of cells?
This is the principle of how you do manage that
update OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=c:\test.xls;hdr=no',
'SELECT * FROM [Sheet1$b7:b7]') set f1 = -99
You can also add formulas to Excel using this:
update OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=c:\test.xls;hdr=no',
'SELECT * FROM [Sheet1$b7:b7]') set f1 = '=a7+c7'
Exporting with column names using T-SQL
Member Mladen Prajdic also has a blog entry on how to do this here
References: www.sqlteam.com (btw this is an excellent blog / forum for anyone looking to get more out of SQL Server).
If you are looking for ad-hoc items rather than something that you would put into SSIS. From within SSMS simply highlight the results grid, copy, then paste into excel, it isn't elegant, but works. Then you can save as native .xls rather than .csv
Here's a video that will show you, step-by-step, how to export data to Excel. It's a great solution for 'one-off' problems where you need to export to Excel:
Ad-Hoc Reporting
It's a LOT easier just to do it from within Excel.!!
Open Excel
Data>Import/Export Data>Import Data
Next to file name click "New Source" Button
On Welcome to the Data Connection Wizard, choose Microsoft SQL Server.
Click Next.
Enter Server Name and Credentials.
From the drop down, choose whichever database holds the table you need.
Select your table then Next.....
Enter a Description if you'd like and click Finish.
When your done and back in Excel, just click "OK"
Easy.
Create the excel data source and insert the values,
insert into OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=D:\testing.xls;',
'SELECT * FROM [SheetName$]') select * from SQLServerTable
More informations are available here
http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=49926
You could always use ADO to write the results out to the worksheet cells from a recordset object
A handy tool Convert SQL to Excel converts SQL table or SQL query result to Excel file without programming.
Main Features
- Convert/export a SQL Table to Excel file
- Convert/export multiple tables (multiple query results) to multiple Excel worksheets.
- Allow flexible TSQL query which can have multiple SELECT statements or other complex query statements.
B. Regards,
Alex
There exists several tools to export/import from SQL Server to Excel.
Google is your friend :-)
We use DbTransfer (which is one of those which can export a complete Database to an Excel file also) here: http://www.dbtransfer.de/Products/DbTransfer.
We have used the openrowset feature of sql server before, but i was never happy with it, becuase it's not very easy to use and lacks of features and speed...
Try the 'Import and Export Data (32-bit)' tool. Available after installing MS SQL Management Studio Express 2012.
With this tool it's very easy to select a database, a table or to insert your own SQL query and choose a destination (A MS Excel file for example).
you can right click on a grid of results in SQL server, and choose save as CSV. you can then you can import this into Excel.
Excel gives you a import wizard, ensure you select comma delimited. it works fine for me when i needed to import 50k+ records into excel.
Check this.
Query -> Query Options.
Results -> Grid -> Include column headers when copying or saving the results