Import data from Excel into SQL Server - sql-server

I want to import an Excel file into SQL Server but I face an error.
My code:
create table test
(
AccountNumber varchar(50),
AccountName varchar(50),
ParentAccountNumber varchar(50)
)
select *
into test
FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=D:\testing.xls;HDR=YES',
'SELECT * FROM [Sheet1$]')
Error:
Msg 7302, Level 16, State 1, Line 10
Cannot create an instance of OLE DB provider "Microsoft.Jet.OLEDB.4.0" for linked server "(null)".
Note:
Excel version : 2007
SQL Server version : 2012

If you are not aware of writing scripts, you can do it by wizard itself.
Right click the DB name you want to import your excel file into. select Task-> Import.
New wizard will open and select the source as Microsoft excel and destination as Sql server, and give the authentication.
Rest all are self expainable.
You can preview the data before you import and you can control the columns you want to import.
Atlast click on finish to run the package.
Will acknowledge you for the successfull import.

Try this after table creation,
INSERT INTO test (AccountNumber , AccountName , ParentAccountNumber)
SELECT *
FROM OPENROWSET ('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=D:\testing.xls;HDR=YES',
'SELECT * FROM [Sheet1$]');

Try running the below code:
EXEC master.dbo.sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0' , N'AllowInProcess' , 1
GO
EXEC master.dbo.sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0' , N'DynamicParameters' , 1
GO
select * FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0',
'Excel 12.0;Database=D:\testing.xls;HDR=YES',
'SELECT * FROM [Sheet1$]')
Make sure your excel sheet is closed when you are running this code.

Related

Insert from SQL to SQLBase with linked Server

how can i insert from SQL Server to a SQLBase Database using linked Server?
Here are various examples of the correct syntax for SQLServer to SQLBase assuming your LinkedServer is called 'ISLANDLINK' . Note the two dots.
or Go here for the full script and explanation : SQLServer to SQLBase via LinkedServer
or Go here for another example: SQLServer to SQLBase via LinkedServer (more)
--Select:
SELECT * FROM OPENQUERY( ISLANDLINK, 'Select * from SYSADM.BUDGET where DEPT_ID = ''MIS'' ')
--Update:
UPDATE [ISLANDLINK]..[SYSADM].[BUDGET]
SET [BGT_YEAR] = 2016
WHERE DEPT_ID = 'MIS'
GO
--Insert:
INSERT INTO [ISLANDLINK]..[SYSADM].[EMPLOYEE]
([EMPLOYEE_ID]
,[LAST_NAME]) VALUES (99 ,'PLUMAS' )
GO
--Delete:
DELETE FROM [ISLANDLINK]..[SYSADM].[EMPLOYEE]
WHERE [LAST_NAME] = 'PLUMAS'

Export xlsx Files out of a SQL Server database

I'm trying to save Excel files in my SQL Server database as BLOB and export them.
Importing the file was quiet easy, but when I'm trying to export them to the file system, the file is damaged and unreadable.
I was quite shocked, because I thought Microsoft wouldn't have much problems importing and exporting their own file types.
INSERT INTO TestBlob(tbName, tbDesc, tbBin)
SELECT
'testfile.xlsx', 'testfile', BulkColumn
FROM
OPENROWSET (Bulk 'C:\temp\testfile.xlsx', Single_Blob) AS tb
I already tried to export it by bcp but I just got a corrupted file.
Do I have to provide a special format file for xlsx files? Are there any other ways to get the xlsx files out of the database?
Thanks in advance
BR. RF
EXEC sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
EXEC sp_configure 'Ad Hoc Distributed Queries', 1;
GO
RECONFIGURE;
GO
USE [AdventureWorks];
GO
INSERT INTO OPENROWSET ('Microsoft.Jet.OLEDB.4.0', 'Excel 8.0;Database=c:\contact.xls;',
'SELECT * FROM [Sheet1$]')
SELECT TOP 5 FirstName, LastName
FROM Person.Contact
GO
https://blog.sqlauthority.com/2008/01/08/sql-server-2005-export-data-from-sql-server-2005-to-microsoft-excel-datasheet/
Or . . .
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'
As an alternative, you could 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.

copy results of a view query into azure sql

I'm trying to create historic data for my company; previously i asked how to copy a table with a timestamp into the same mssql database. realistically, it dawned on me that what i really need to do is the following
1) log onto my local mssql box
2) run a query of a view (select * from view_whatever)
3) copy the results of the query and add a timestamp into another database, hosted using azure SQL
if i were doing this from the same database to another table, i'd something like this:
DECLARE #copyDate DATETIME2 = CURRENT_TIMESTAMP
INSERT INTO Hst_Opportunities
SELECT OppName, Oppvalue, #copyDate AS copyDate
FROM dbo.opportunities
the from part is what im struggling with - how do i copy cross server and database when the source database is MSSQL and the target is Azure SQL?
Based on my test, it appears you could create a linked server on your local box and insert the data using four part name:
EXEC master.dbo.sp_addlinkedserver #server = N'SQLAZURE', #srvproduct=N'sqlazure', #provider=N'SQLNCLI', #datasrc=N'NAME.database.windows.net', #catalog=N'TestDb'
EXEC master.dbo.sp_addlinkedsrvlogin #rmtsrvname=N'SQLAZURE',#useself=N'False',#locallogin=NULL,#rmtuser=N'USERNAME',#rmtpassword='Password'
GO
DECLARE #copyDate DATETIME = CURRENT_TIMESTAMP;
INSERT INTO [SQLAZURE].[TestDb].[Schema].[Table]
SELECT TOP (10)
[Column1]
,[Column2]
,#copyDate AS copyDate
FROM [Localdb].[Schema].[View];

Batch file to insert Excel data into SQL Server table

I'm trying to write a batch file that takes information from an Excel spreadsheet and adds new rows into my SQL Server.
I think what I have currently is nearly there. As it runs and says a line has been updated, but it hasn't.
This is my batch file:
#echo off
copy \\RDS-2012-C\2012_N_Drive\Operations\Reports\Metrics\sql2.xlsx C:\ACCESS_SQLSVR\import_location
sqlcmd -S RDS-2012-G\RDS_SQL -d Master -i C:\ACCESS_SQLSVR\import_location\sesame_import.sql
pause
And this is what it runs:
EXEC sp_configure 'Show Advanced Options', 1;
RECONFIGURE
GO
EXEC sp_configure 'Ad Hoc Distributed Queries', 1;
RECONFIGURE
GO
EXEC sp_MSSet_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'AllowInProcess', 1;
GO
EXEC sp_MSSet_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'DynamicParameters', 1;
GO
SELECT * FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0',
'Excel 12.0;Database=C:\ACCESS_SQLSVR\import_location\sql2.xlsx;HDR=YES;IMEX=1',
'SELECT * FROM [SQL$]')
GO
Do I simply need a different command instead of SELECT?
Also, the full database and table in the SQL Server is called:
Sesame_FTest.dbo.SQL
Running this when the table doesn't exist results in the table being created and filled with the Excel information. But running it a second time with a new Excel doesn't update like I thought it would.
Try it like this . . .
------ INSERT INTO NON-EXISTING TABLES
USE [YourDatabase]
GO
SELECT * INTO tbl_Mapping
FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0',
'Excel 12.0 Xml;HDR=YES;Database=C:\Users\rshuell001\Desktop\State Street\Final Deliverables\Raw Data\Mapping.xlsx',
'SELECT * FROM [Mapping$]')
SELECT * INTO tbl_Data
FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0',
'Excel 12.0 Xml;HDR=YES;Database=C:\Users\rshuell001\Desktop\State Street\Final Deliverables\Raw Data\Data.xlsx',
'SELECT * FROM [Data$]')
OR . . .
------ INSERT INTO EXISTING TABLES
USE [YourDatabase]
GO
Insert INTO tbl_Mapping
SELECT * FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0',
'Excel 12.0 Xml;HDR=YES;Database=C:\Users\rshuell001\Desktop\State Street\Final Deliverables\Raw Data\Mapping.xlsx',
'SELECT * FROM [Mapping$]')
Insert INTO tbl_Data
SELECT * FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0',
'Excel 12.0 Xml;HDR=YES;Database=C:\Users\rshuell001\Desktop\State Street\Final Deliverables\Raw Data\Data.xlsx',
'SELECT * FROM [Data$]')

SQL Server 2012 - Insert into linked server table using openquery

I have a linked server Remoteserver containing a table that holds file and folder names from a dir
When I am on the remote server I can run a built in procedure (xp_dirtree) and populate the 'files' table but what i need to do is to run a query from the local SQL server that does this:
Delete all records from the [Files] table on Remoteserver
Insert data that comes from the stored procedure:
INSERT [Remoteserver].[dbo].[files] (subdirectory,depth,isfile)
EXEC master.sys.xp_dirtree '\\Fileserver\DBBackup',1,1;
Select the 'subdirectory' column
I tried some things using openquery and i am able to select existing records but unable to do the insert.
Any help is appreciated.
Try this
INSERT INTO OPENQUERY([Remoteserver]
,'SELECT subdirectory, depth, [file] FROM [RemoteDB].[dbo].[files]')
EXEC master.sys.xp_dirtree '\\fileserver\DBBackup', 1, 1;
OR
INSERT INTO OPENQUERY([Remoteserver]
,'SELECT subdirectory,depth, [file] FROM [RemoteDB].[dbo].[files]')
select * from OPENQUERY([another_server_name], 'master.sys.xp_dirtree ''\\fileserver\DBBackup\temp'', 1, 1');
But in general you do not need to use OPENQUERY at all if Fileserver and Remoteserver are accessible from the local machine.
INSERT INTO [Remoteserver].[RemoteDB].[dbo].[files] (subdirectory, depth, isfile)
EXEC master.sys.xp_dirtree '\\Fileserver\DBBackup',1,1;

Resources