简体   繁体   中英

SQL Server export stored procedure results to CSV file keeping char(9) format

I'm having a problem with exporting the results of a stored procedure to a csv file and keeping the results as a 9 character string. The results of the stored procedure is a simple one column output which looks fine when executed in SSMS but the returned values in the csv that have leading zeros are being returned without the zeros. The table column is type varchar(13) and I have done a convert to try and keep the leading zeros from being dropped but no luck.

Here is the stored procedure:

SELECT DISTINCT
convert(char(8),n.NIIN)
FROM IMMS_ELEC.dbo.NIINList n

Here is the simple BCP script I'm using:

DECLARE @string AS NVARCHAR(4000)
SELECT    @string = 'BCP "exec CPLINK_Dev.dbo.spSelectLOG_NiinDistinct"
QUERYOUT:\data.csv -c -T -t'
exec master.dbo.xp_cmdshell @string

Excel loves to think it knows how to format your data better than you do... Here's a trick you can use to outsmart it. Open a new spreadsheet, select all cells and change the type to text (from general), then copy your data from notepad (or SSMS), paste it into Excel, and use text to columns if you have to... Excel should stop messing with your formats then.

You can also probably do the same thing with import data from Excel, but I find the first much more effective and you can use it to copy and paste directly from SSMS grid results as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM