The following simple scripts try to demonstrate how bcp can be used to export and import data from and into tables on SQL Server.
Export and import tables
Two tables with data to be exported (exp_test_p and exp_test_c) as well as the corresponding import tables (imp_test_p and imp_test_c) are created:
set nocount on
create table exp_test_p (
id integer primary key,
txt varchar(10)
);
create table exp_test_c (
id_p integer references exp_test_p,
val decimal(4,1)
);
select * into imp_test_p from exp_test_p;
select * into imp_test_c from exp_test_c;
The following batch file exports a subset of the data into the files data_p.exp and data_c.exp.
The subset of the data is specified with the variable%CONDITION_C%.
The -t flag specifies the field separator. In our case, the vertical bar.
The -T flag tells bcp to use a trusted connection.
setlocal
rem
rem Condition to select only select a subset of (child-) data:
rem
set CONDITION_C=val between 10 and 40
rem
rem Create SQL statement for parent data:
rem
set SQLSTMT= ^
select ^
* ^
from ^
exp_test_p ^
where ^
id in (select id_p from exp_test_c where %CONDITION_C%)
rem
rem Export data
rem
bcp "%SQLSTMT%" queryout data_p.exp -c -T -t"|" -d %DB%
rem
rem Create SQL statement for child data:
rem
set SQLSTMT= ^
select ^
* ^
from ^
exp_test_c ^
where ^
%CONDITION_C%
rem
rem Export data
rem
bcp "%SQLSTMT%" queryout data_c.exp -c -T -t"|" -d %DB%