Share via

Export Table to CSV

Manny 151 Reputation points
2023-03-13T02:43:21.8166667+00:00

Hi

I would like to output the contents of the table (including headers) to a CSV file. My script below is giving me "Access is Denied" error. How do I modify the script so it works?

-- Enable Xp_cmdShell  
EXECUTE sp_configure 'show advanced options', 1    
RECONFIGURE     
EXECUTE sp_configure 'xp_cmdshell', 1  
RECONFIGURE  

EXEC master..xp_cmdshell 'sqlcmd -s, -W -Q "SELECT* FROM DBO.Table" | findstr /v /c:"-" /b > "C:\Users\Me\file.csv"'

-- Disable Xp_cmdShell 
EXEC sp_configure 'show advanced options', 1
RECONFIGURE
EXEC sp_configure 'xp_cmdshell', 0
RECONFIGURE
GO

Thank you

SQL Server | Other
SQL Server | Other

Additional SQL Server features and topics not covered by specific categories


1 answer

Sort by: Most helpful
  1. Olaf Helper 47,621 Reputation points
    2023-03-13T07:12:18.95+00:00

    "Access is Denied"
    "C:\Users\Me\file.csv"'

    Of course you get access denioed, it's your user folder and only your account (+admins) to have access permissions for, but not SQL Server service account. Use a more approbiate folder and set access permissions for.

    Was this answer helpful?

    0 comments No comments

Your answer

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