SQL query from import wizard - sql-server

I imported an Excel (.xlsx) file into a table in SQL Server using the import wizard.
I want to get the query used to import so that I can store it and incorporate it in a SQL Server stored procedure. How can I get that query?

You can't get the specific query used by the wizard, you can only save the SSIS package for later use. You can do this with other methods, via sql, which you can include in your stored procedure as explained in the official documentation.
OPENROWSET
sp_configure 'show advanced options', 1;
RECONFIGURE;
GO
sp_configure 'Ad Hoc Distributed Queries', 1;
RECONFIGURE;
GO
USE ImportFromExcel;
GO
SELECT * INTO Data_dq
FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0',
'Excel 12.0; Database=C:\Temp\Data.xlsx', [Sheet1$]);
GO
BULK INSERT
USE ImportFromExcel;
GO
BULK INSERT Data_bi FROM 'C:\Temp\data.csv'
WITH (
FIELDTERMINATOR = ',',
ROWTERMINATOR = '\n'
);
GO

Related

How to import data from excel file into sql server DB by script

I am trying to import data from Excel into SQL.
I saw all kinds of answers on Google, but I didn't really find the right answer
I would really appreciate any help on this matter...
I have an excel file in a folder and I want to create a script that will load all the data from this excel file into a dedicated table in my DB
The script should be written in SQL Server
Does anyone have a simple way to do this?
I try this code:
sp_configure 'show advanced options', 1;
RECONFIGURE;
GO
sp_configure 'Ad Hoc Distributed Queries', 1;
RECONFIGURE;
GO
USE Diyur;
GO
SELECT * INTO Data_dq
FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0',
'Excel 12.0; Database=C:\File.xls', [Sheet1$]);
GO
But I get this error:
Msg 7403, Level 16, State 1, Line 12 The OLE DB provider
"Microsoft.ACE.OLEDB.12.0" has not been registered. Blockquote
After many google searches and my many attempts I found the correct code:
declare #SQL nvarchar(max) = '
CREATE TABLE #TempTable
( [Field1] nvarchar(max) NULL,
[Field2] nvarchar(max) NULL,
[Field3] nvarchar(max) NULL );
BULK INSERT #TempTable FROM ''<FullPath>\FileName.csv'' WITH --if the path is in the network - need to write the Full-path of the drive
(
KEEPIDENTITY,
FIELDTERMINATOR = '','',
MAXERRORS = 10000,
KEEPNULLS,
ROWTERMINATOR=''\n'',
FIRSTROW = 2,
CODEPAGE = ''1255''
);
select * from #TempTable
Insert into TableNameInDB(Field1,Field2,Field3)
select * from #TempTable
'
EXEC sp_executesql #SQL

Export the content of a SQL Server table to a CSV without using xp_cmdshell

I need to export the content of a Table into a file CSV.
I tried to use the execution of a xp_cmdshell from a stored procedure but it doesn't work because this component is turned off as part of the security configuration for this server.
Do you know others way to write a file from a stored procedure?
Here are a couple of methods you can try :
1. Using BCP
syntax :
bcp "SELECT * FROM Database.dbo.input" queryout C:\output.csv -c -t',' -T -S .\SQLEXPRESS
microsoft document : BCP Utility
2. Second Method(for excel, but should work for csv too) :
Insert into OPENROWSET
('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=D:\testing.xls;',
'SELECT * FROM [SheetName$]') select * from SQLServerTable
For this, you need to enable adhoc distributed queries by following command :
EXEC sp_configure 'show advanced options', 1
RECONFIGURE
GO
EXEC sp_configure 'ad hoc distributed queries', 1
RECONFIGURE
GO
you might encounter a link server error. So you should refer : this stack overflow solution

How to Extract the Query result to directly to .XLSx File

Could you please let me know how to Extract Query result to Excel sheet in SQL server,
My query is batch Job, so I need to keep all my query result in Excel sheet, Later I will do FTP.
Please suggest me is there any way to do in SQL Server.
Note :- Not using Result to File in Management studio, I need to know using any scripts in Sql
Try this,
First Enable Ad Hoc Distributed Queries
sp_configure 'show advanced options', 1;
RECONFIGURE;
sp_configure 'Ad Hoc Distributed Queries', 1;
RECONFIGURE;
GO
Export Result Query to Excel File
DECLARE #STR_QUERY AS NVARCHAR(MAX)
DECLARE #FILE_ATT_PATH NVARCHAR(50) ='D:\MYEXCEL'+REPLACE(CONVERT(VARCHAR,GETDATE(),113),':','')+'.XLS';
SET #STR_QUERY =
N'INSERT INTO OPENROWSET(''Microsoft.Jet.OLEDB.4.0'', ''Excel 8.0;Database='+ #FILE_ATT_PATH +';'',''SELECT CusSName FROM [Sheet1$]'')
SELECT CusSName FROM [dbo].[MasterCustomer]'
EXEC sp_executesql #STR_QUERY

stored procedure to export to CSV with BCP

I need to create an on-demand export of user data on our website. The user clicks an export button, classic ASP code executes a stored procedure that generates a file via BCP, and the user is prompted to download it.
I've created the sproc, and its working flawlessly when executed from SSMS. The catch is getting it to work from the site with the limited privileges granted to the account connecting to SQL from the website. Here is a snippet:
-- INSERT TEMP DATA
INSERT INTO t_users_tempExport
SELECT * FROM #tempExport
-- show advanced options
EXEC sp_configure 'show advanced options', 1
RECONFIGURE
-- enable xp_cmdshell
EXEC sp_configure 'xp_cmdshell', 1
RECONFIGURE
-- hide advanced options
EXEC sp_configure 'show advanced options', 0
RECONFIGURE
-- EXPORT TO CSV
DECLARE #sql varchar(8000)
SELECT #sql = 'bcp "select * FROM DBNAME.dbo.tempExport WHERE scopeID='''+#randomString+'''" '
+ 'queryout C:\temp\exportResidents_'+CONVERT(varchar(max),#userID)+'.csv -c -t, -T -S'
+ ##servername
EXEC master..xp_cmdshell #sql
-- RETURN FILE NAME
SELECT 'C:\temp\export_'+CONVERT(varchar(max),#userID)+'.csv' AS fileName
The issue is that I cannot enable xp_cmdshell with the privledges granted to the account that is connecting to SQL from the website. Im kind of at a loss as to how to proceed.
Is it possible to include the sysadmin credentials in the call to BCP? Is there some easier option or work around?
I ended up going a completely different route. I created the CSV file from pure ASP code, only using the sproc to return the data.

Using query export SQL Server 2008 table to Excel Sheet

How to export sql server table data to excel sheet.
insert into OPENROWSET('Microsoft.ACE.OLEDB.12.0',
'Excel 12.0;Database=D:\Book1.xlsx;',
'SELECT * FROM [SheetName$]') select TOP 5 CustomerID from Customers
I used the above query but it shows following error
Msg 7308, Level 16, State 1, Line 1 OLE DB provider
'Microsoft.ACE.OLEDB.12.0' cannot be used for distributed queries
because the provider is configured to run in single-threaded apartment
mode.
I have found the solution
sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Ad Hoc Distributed Queries', 1;
GO
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
insert into OPENROWSET('Microsoft.ACE.OLEDB.12.0',
'Excel 12.0;Database=D:\Book1.xls;',
'SELECT * FROM [Sheet1$]') select TOP 5 CustomerID from Customers
Its working fine

Resources