How to produce an csv output file from stored procedure in SQL Server

后端 未结 7 893
孤独总比滥情好
孤独总比滥情好 2020-12-03 14:01

Is it possible to generate a csv file from a stored procedure in SQL Server? I created my stored procedure and I want to stored some result as csv, does someone know how to

7条回答
  •  忘掉有多难
    2020-12-03 15:04

    You can do this using OPENROWSET as suggested in this answer. Reposting Slogmeister Extrarodinare answer:

    Use T-SQL

    INSERT INTO OPENROWSET ('Microsoft.ACE.OLEDB.12.0','Text;Database=D:\;HDR=YES;FMT=Delimited','SELECT * FROM [FileName.csv]')
    SELECT Field1, Field2, Field3 FROM DatabaseName
    

    But, there are couple of caveats:

    1. You need to have the Microsoft.ACE.OLEDB.12.0 provider available. The Jet 4.0 provider will work, too, but it's ancient, so I used this one instead.

    2. The .CSV file will have to exist already. If you're using headers (HDR=YES), make sure the first line of the .CSV file is a delimited list of all the fields.

提交回复
热议问题