title: SQL Server stored procedure to export Select Result to CSV
body: <p>In my stored procedure, I want to export select result to a <code>.CSV</code> file. I need to write a stored procedure which selects some data from different tables and saves it to a <code>.CSV</code> file.  </p>
  
  <p>Selecting part is ready </p>
  
  <pre><code> SELECT DISTINCT 
                    PER.NREGNUMBER_PERNUM AS [Registration Number], 
                    PER.CFAMNAME_PER AS [Family Name], 
                    PER.CGIVNAME_PER AS [Given Name], 
                    CONVERT(varchar(10), CONVERT(date, PER.DBIRTHDATE_PER, 106), 103) AS [Birth Date], 
                    PER.CGENDER_PERGEN as [Gender],
                    PHONE.MOBILE_NUMBER
          FROM      PERSON AS PER 
                    LEFT OUTER JOIN
                    PHONE ON PER.NREGNUMBER_PERNUM = PHONE.NREGNUMBER_PPHPER AND PHONE.CPRIMARY_PPH = 'Y'
  </code></pre>