简体   繁体   English

关于sql-server批量插入的咨询

[英]Consultation about bulk insert in sql-server

I have C# WinForm program that i need to insert sql-server.我有需要插入 sql-server 的 C# WinForm 程序。

The file is Text (Tab delimited).该文件是文本(制表符分隔)。

Sometimes it contains (3 columns):有时它包含(3 列):

BAR    DES     MAK
111    aaa     222
333    bbb     333
.
.

and sometimes it contains (5 columns):有时它包含(5 列):

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: sql-server 表是 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如果有 5 列它运行良好,如果有 3 列它崩溃

I searched and found no solution.我搜索并没有找到解决方案。 Anyone have an idea?有人有想法吗?

BULK INSERT is not very flexible. BULK INSERT 不是很灵活。 A solution would be to load the columns into a table with only one varchar column and then do your splitting/parsing later on.一种解决方案是将列加载到只有一个 varchar 列的表中,然后稍后进行拆分/解析。

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')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM