Alternative solution by presenting process output as file
There is an other convenient way to solve this. My solution is good if you want to upload a simple CSV, for more complex cases write a format file.
Using hex code for linefeed (-r 0x0a
) would be also convenient, but it did not work for me for BCP version 17.6.0001.1 on Ubuntu 18.04.
So I used a little trick instead:
Replace unix line-endings with sed
, and present its output stream as a file. The relevant part of the code:
<(< iris.csv sed 's/\r*$/\r/')
As you can below see the output of sed
is presented as a file:
ls <(< iris.csv sed 's/\r*$/\r/')
output:
/proc/self/fd/11
A whole example
I have the iris.csv
in the working directory:
> head -n 5 iris.csv
sepal_length,sepal_width,petal_length,petal_width,species
5.1,3.5,1.4,0.2,setosa
4.9,3.0,1.4,0.2,setosa
4.7,3.2,1.3,0.2,setosa
4.6,3.1,1.5,0.2,setosa
I can load into MS SQL using bcp like this:
query=$(cat << EOF
IF NOT EXISTS (SELECT * FROM sysobjects WHERE name='iris' and xtype='U')
CREATE TABLE iris (
sepal_length FLOAT NOT NULL,
sepal_width FLOAT NOT NULL,
petal_length FLOAT NOT NULL,
petal_width FLOAT NOT NULL
)
GO
EOF
)
sqlcmd \
-S localhost,31433 \
-E \
-d "testdb" \
-Q "$query"
bcp \
iris in <(< iris.csv sed 's/\r*$/\r/') \
-S localhost,31433 \
-T \
-d "testdb" \
-n \
-t ","
Notice
presenting process output stream as a file with this syntax is a bashism so will not work with some other shells such as dash. It will work with zsh
I used windows integrated authentication for AD, yes on Linux which can do this with kerberos. Thats why the -E
flag for sqlcmd
and the -T
flag for bcp
.