How to Extract the Query result to directly to .XLSx File - sql-server

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

Related

SQL query from import wizard

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

SQL Server - can enabling and disabling xp_cmdshell in multiple queries be harmfull?

I am currently working at one of my clients SQL-Server environment. A year ago I was asked to implement a .csv report generation in a Maintenance Plan I was working on. To do so, I have enabled xp_cmdshell option on the server and used bcp utility. However, a programmer from the other company recently added a stored procedure in which he enables xp_cmdshell option at the beginning of procedure and disables it (sets to 0) at its end. This feature have caused my Maintenance Plan to fail at the report generation step.
Since I'm not allowed to change his code I was asked to include similar enabling/disabling feature in my scripts. Here is example of code I found and used:
declare #prevAdvancedOptions int;
declare #prevXpCmdshell int;
select #prevAdvancedOptions = cast(value_in_use as int) from sys.configurations where name = 'show advanced options';
select #prevXpCmdshell = cast(value_in_use as int) from sys.configurations where name = 'xp_cmdshell';
if (#prevAdvancedOptions = 0)
begin
exec sp_configure 'show advanced options', 1;
reconfigure;
end;
if (#prevXpCmdshell = 0)
begin
exec sp_configure 'xp_cmdshell', 1;
reconfigure;
end;
--- doing some work here ---
if (#prevXpCmdshell = 0)
begin
exec sp_configure 'xp_cmdshell', 0;
reconfigure;
end;
if (#prevAdvancedOptions = 0)
begin
exec sp_configure 'show advanced options', 0;
reconfigure;
end;
The thing is I'm not completly sure about the safety of this solution but I don't want to redesign the code I wrote. I am also using xp_cmdshell feature in some other scripts.
The question is: Is it possible that execution of Script A (used by my maintenance plan) can be affected with disabling xp_cmdshell in Script B (used in the stored procedure) when they are executed at the same time?
I have done some research about SQL-Server Query Processor to understand how it works and executes the queries but could not find an answer to this question.
I will appreciate any of your suggestions!

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

SQL Server xp_cmdshell fail to export data

I want to export values from a column (TcpIpAddress) from a table called dbo.DimServere to a plain text (located in the server). I have sysadmin rights.
-- To allow advanced options to be changed.
EXEC sp_configure 'show advanced options', 1;
GO
-- To update the currently configured value for advanced options.
RECONFIGURE;
GO
-- To enable the feature.
EXEC sp_configure 'xp_cmdshell', 1; -- 1 for at enable
GO
-- To update the currently configured value for this feature.
RECONFIGURE;
GO
-- Extracting information from the databse
EXEC xp_cmdshell 'bcp "SELECT TcpIpAddress FROM [SIT-DVH].[dbo].[DimServere]" queryout "C:\Users\b013904\Desktop\Output\bcptest.txt" -T -c -t,'
-- To allow advanced options to be changed.
EXEC sp_configure 'show advanced options', 1;
GO
-- To update the currently configured value for advanced options.
RECONFIGURE;
GO
-- To disable the feature.
EXEC sp_configure 'xp_cmdshell', 0; -- 0 for at disable
GO
-- To update the currently configured value for this feature.
RECONFIGURE;
GO
However, when I run this script, I get the following message and no file is been created:
What am I doing wrong?
The path in that bcp statement will be relative to the server since you're executing it on the server.
Does that path exist on the server?
Also, try changing the path to something more accessible like c:\output. .. then you can play around with the permissions on that folder to ensure that is not a os permission that's causing the statement to fail.
Hope that helps

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.

Resources