BCP program or the bulk copy program utility is used to extract data from a table into a flat file but can we have the column names of a table along with the table's data in the file?
The bcp utility does not offer a switch to extract column name so we need to have a workaround to achieve the same and what could that be? So, to tackle this situation here is Views to the rescue. To explain this concept we will be creating a table Employee with the following definition -
create table Employee
(
EmpId int,
EmpName varchar(100),
Age int,
Salary float
)
go
Now, we will create the following view -
create view V as
select
"EmpId",
"EmpName",
"Age",
"Salary"
from
Employee
where 1=1
union
select
convert(varchar, EmpId),
EmpName,
convert(varchar, Age),
convert(varchar, Salary)
from
Employee
go
As we can see here that we have created a view V which will do a union of column names and columns data. On executing this view we get the column name and the data both in a single resultset.
Now what remains is running the bcp command to extract the data to a flat file and the command to accomplish this is as follows -
bcp Database.Owner.ViewName out FilePath -SSERVERNAME -UUSERNAME -PPASSWORD -c -t,
and thats it.. We will get the column name and the data in a flat file simply by creating a view. Isn't it simple?
The bcp utility does not offer a switch to extract column name so we need to have a workaround to achieve the same and what could that be? So, to tackle this situation here is Views to the rescue. To explain this concept we will be creating a table Employee with the following definition -
create table Employee
(
EmpId int,
EmpName varchar(100),
Age int,
Salary float
)
go
Now, we will create the following view -
create view V as
select
"EmpId",
"EmpName",
"Age",
"Salary"
from
Employee
where 1=1
union
select
convert(varchar, EmpId),
EmpName,
convert(varchar, Age),
convert(varchar, Salary)
from
Employee
go
As we can see here that we have created a view V which will do a union of column names and columns data. On executing this view we get the column name and the data both in a single resultset.
Now what remains is running the bcp command to extract the data to a flat file and the command to accomplish this is as follows -
bcp Database.Owner.ViewName out FilePath -SSERVERNAME -UUSERNAME -PPASSWORD -c -t,
and thats it.. We will get the column name and the data in a flat file simply by creating a view. Isn't it simple?