Question

I need to upload following data to excel file using bcp command

id       |  phoneNo     | IsValid          
--------------------------------------
1        |  011         |    1
2        |  011         |    1
3        |  022         |    1
4        |  022         |    1
5        |  033         |    1
6        |  011         |    1

Problem occurs when i trying to export telephone numbers. in excel leading zero's missing.

What i have tried so far-

alter procedure [dbo].[proc_generate_excel_with_columns]
(       @SERVERNAME VARCHAR(100), 
        @db_name varchar(100),
        @table_name varchar(100),
        @file_name varchar(100)     
)
as

--Generate column names as a recordset
declare @columns varchar(8000), @sql varchar(8000), @data_file varchar(100),@schemaTable varchar(100)

--set @table_name='test'
set @schemaTable='dbo.'+ @table_name

select
        @columns=coalesce(@columns+',','')+column_name+' as '+column_name
from
        information_schema.columns
where
        table_name=@table_name


select @columns=''''''+replace(replace(@columns,' as ',''''' as '),',',',''''')

--Create a dummy file to have actual data
select @data_file=substring(@file_name,1,len(@file_name)-charindex('\',reverse(@file_name)))+'\data_file.xls'

--Generate column names in the passed EXCEL file
set @sql='exec master..xp_cmdshell ''bcp " select * from (select '+@columns+') as t" queryout "'+@file_name+'" -c -S'+@SERVERNAME+' -T '''

exec(@sql)

--Generate data in the dummy file

set @sql='exec master..xp_cmdshell ''bcp "select * from '+'['+@db_name+']'+'.'+@schemaTable+'" queryout "'+@data_file+'" -c -S'+@SERVERNAME+' -T '''
PRINT @sql
exec(@sql)

--Copy dummy file to passed EXCEL file
set @sql= 'exec master..xp_cmdshell ''type '+@data_file+' >> '+@file_name+''''

exec(@sql)

--Delete dummy file
set @sql= 'exec master..xp_cmdshell ''del '+@data_file+''''
exec(@sql)

How can i solve this problem? I found Solution here , but it mentioned use code like this.

SELECT '="' + phoneNo+ '"' from Phone

but it seems i can't come up with this solution. How can i overcome with this problem.

Thanks

Was it helpful?

Solution

For this i have created intermediate table, i use that table in bcp command.

create table temp_WriteDataToFile(PHONE text, IsValid varchar(1))

insert into temp_WriteDataToFile 
 select '="'+ PHONE +'"',ACMA,convert(varchar(25)) from temp_ProcessData

it need get value in following format :

="011 "

then it will allow to write in excel/csv command with leading zero's

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top