简体   繁体   中英

Consultation about bulk insert in sql-server

I have C# WinForm program that i need to insert sql-server.

The file is Text (Tab delimited).

Sometimes it contains (3 columns):

BAR    DES     MAK
111    aaa     222
333    bbb     333
.
.

and sometimes it contains (5 columns):

BAR    DES     MAK    PRI    MLA
111    aaa     222    1.1    2.2
333    bbb     333    3.3    4.4
.
.

The sql-server table is CatTbl:

BAR nvarchar(250)
DES nvarchar(250)
MAK nvarchar(250)
PRI nvarchar(250)
MLA nvarchar(250)

i try to insert like this:

SQL = @"BULK INSERT CatTbl FROM 'd:\TEST\TEST.txt' WITH (CODEPAGE=1255,FIELDTERMINATOR = '\t')";
Cmd = new SqlCommand(SQL, Conn);
Cmd.ExecuteNonQuery();
Cmd.Dispose();

If there 5 columns it works excellent but if there 3 columns it crashes

I searched and found no solution. Anyone have an idea?

BULK INSERT is not very flexible. A solution would be to load the columns into a table with only one varchar column and then do your splitting/parsing later on.

If the table doesn't match the file, create a view on the table that does, and insert into the view

-- Run this once in SSMS to create the view
CREATE VIEW MyView AS SELECT BAR,DES,MAK FROM CatTbl;

-- If your file has three columns, use this
BULK INSERT MyView FROM 'd:\TEST\TEST.txt' WITH (CODEPAGE=1255,FIELDTERMINATOR = '\t')

-- If your file has five columns, use this
BULK INSERT CatTbl FROM 'd:\TEST\TEST.txt' WITH (CODEPAGE=1255,FIELDTERMINATOR = '\t')

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