Hi @pizaro ,
Welcome to Microsoft Q&A!
The Transact-SQL OPENROWSET could be used to export SQL Server data to an Excel file via SSMS.
First create a blank excel file at the directory of your choosing(for example: C:\SQL\test.xlsx).
Then create procedure like below:
create PROCEDURE dbo.uspGetReportData
@Startdate Date = NULL,
@Enddate DATE = NULL,
@FileID BIGINT = NULL,
@ClientName VARCHAR(50) = NULL
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO OPENROWSET('Microsoft.ACE.OLEDB.12.0','Excel 12.0;
Database=C:\SQL\test.xlsx;','SELECT * FROM [sheet1$]')
SELECT
o.FileID,
dl.AddressLine1 AS [PropertyAddress],
dl.City,
dl.[State],
dl.Zip,
c.ClientName,
o. OrderDate
FROM [dbo].[Orders] o
LEFT JOIN dbo.OrderLoan dl ON dl.OrderLoanID = o.OrderLoanID
LEFT JOIN dbo.Client c ON c.ClientID = o.ClientID
WHERE orderDate >= ISNULL(@Startdate,orderDate)
AND orderDate <= ISNULL(@Enddate,orderDate)
AND FileID IN( ISNULL(@FileID,FileID))
AND c.ClientName IN ( ISNULL(@ClientName,ClientName))
END
Configuring this can be tricky and dependent on your level of permissions. Make sure you have the correct Linked Server/Provider installed (‘Microsoft.ACE.OLEDB.12.0’) And check your Database user settings to this server .
But, when executing the above code, the following error may occur:
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.
To recolve above issue, you could execute below:
EXEC sp_configure 'show advanced options', 1
RECONFIGURE
EXEC sp_configure 'Ad Hoc Distributed Queries', 1
RECONFIGURE
You may also face below issue:
OLE DB provider “Microsoft.ACE.OLEDB.12.0” for linked server “(null)” returned message “The Microsoft Access database engine cannot open or write to the file ”. It is already opened exclusively by another user, or you need permission to view and write its data.”.
Msg 7303, Level 16, State 1, Line 1
This usually happens because of inadequate permissions.
If you face another issue as below:
Msg 213, Level 16, State 1, Line 1
Column name or number of supplied values does not match table definition.
You could open excel file and enter the column names which will represent the column names from the table.
In addition, you could refer more details about this or other methods including SSIS in this link.
Best regards
Melissa
If the answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.