Using OPENROWSET to Export to .csv Not Inserting Rows

David Kingston 21 Reputation points
2022-01-05T19:43:51.73+00:00

When I execute the code below in SSMS I receive the message X rows affected where X is the number of rows in mytable. When I open myfile.csv it remains empty except for the headers which were in the file prior to me executing the INSERT. Is there some additional step I need to take to save myfile.csv? Any advice is appreciated and thanks in advance.

INSERT INTO OPENROWSET ('Microsoft.ACE.OLEDB.12.0','Text;Database=\myfilepath\;HDR=YES;FMT=Delimited','SELECT * FROM myfile.csv]')
SELECT * FROM [dbo].[mytable]

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
14,494 questions
Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,705 questions
{count} votes

2 answers

Sort by: Most helpful
  1. AmeliaGu-MSFT 14,001 Reputation points Microsoft External Staff
    2022-01-06T05:59:48.23+00:00

    Hi DavidKingston-5052,

    Welcome to Microsoft Q&A.

    The OPENROWSET is usually used to access remote data from an OLE DB data source.
    To export data to .csv file, we can use command-line Bcp utility.

    For example:

    bcp "SELECT * FROM dbo.table" queryout C:\temp\test.csv -S servername-d dbname -c -t, -T  
    

    We can also use SQL Server Import and Export Wizard in the SSMS to export data.
    Please refer to Bulk Import and Export of Data and How to export SQL Server data to a CSV file for more information.
    Best Regards,
    Amelia


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    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.


  2. GlockByte 161 Reputation points
    2022-01-08T01:57:59.767+00:00

    I would execute this through powershell or C# rather than all in T-SQL.

    $query = "SELECT * FROM [dbo].[mytable]"  
    $data = Invoke-Sqlcmd -ServerInstance MyServer -Query $query  
    $data | Export-Csv -Append -Path "fullpath\myfile.csv" -NoTypeInformation  
    

    If Invoke-sqlcmd is not on the machine

    Install-Module -Name SqlServer -AllowClobber  
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.