如何将值添加到本地文本文件中的单个空列

How to add values to single empty column from local text file

我有 table 位客户使用 CustomerID、CompanyName、Address Phone

现在我们插入了一个名为 Remarks 的新列,该列为空或 null

我有文本文件要使用带有以下代码的视图 Remarkinsert 批量插入到列中

bulk insert  HRRegion.dbo.Remarksinsert
 From 'C:\Users\SMSTECHLNG50\Documents\remarks..txt'
 with 
 (
 FIELDTERMINATOR = ',',
ROWTERMINATOR = '\n'
)
GO

但是出现错误

Msg 515, Level 16, State 2, Line 9 Cannot insert the value NULL into column 'CustomerID', table 'HRRegion.dbo.Customers'; column does not allow nulls. INSERT fails. The statement has been terminated.

我想也是在这里,你只能插入整行或什么都不插入。

如果您的客户 table 看起来像这样:

customer
custid|co_name        |addr                     |phone            |remarks
    42|Laverda        |Breganze, Italy          |+39 6 233 84 81  |(NULL)
    43|Benelli        |Pesaro, Italy            |+39 8 284 55 32  |(NULL)
    44|Ural           |Irbit, Russia            |+7 14 526 22 2342|(NULL)
    45|Dnepr          |Kiew, Ukraine            |+380 526 22 2342 |(NULL)
    46|Harley Davidson|Milwaukee, US            |+1 802 223 4444  |(NULL)
    47|Honda          |Tokyo, Japan             |+81 82 555 4123  |(NULL)
    48|Moto Guzzi     |Mandello del Lario, Italy|+39 6 423 04 72  |(NULL)
    49|Ducati         |Bologna, Italy           |+39 7 722 04 43  |(NULL)
    50|Norton         |Birmingham, UK           |+44 7234 723 4423|(NULL)
    51|Matchless      |Plumstead, London, UK    |+44 8021 612 0843|(NULL)
    52|Brough         |Nottingham, UK           |+44 5812 512 4883|(NULL)

(好吧,您使用 ALTER TABLE ... 添加 remarks 列),然后,我希望您在备注中提到的文件看起来有点像这样:

remarks
custid|remarks
    42|built also tractors, closed now
    43|first series 6-cylinder motorbike
    44|old style sidecar rigs with modern engine
    45|old style sidecar rigs, permanent two-wheel drive
    46|the american classic
    47|builders of the CB 750 four and the gold wing
    48|famous for horizontal singles and 90° V twins
    49|90° V twin bikes with lateral crankshaft
    50|english classic, still alive
    51|english classic, closed now
    52|probably the finest motorcycles ever built

因此,您将构建一个 remarks_stg table:

CREATE TABLE remarks_stg (
  custid  SMALLINT    NOT NULL
, remarks VARCHAR(50) NOT NULL
);

然后,您只加载那个暂存 table 与数据文件如上所述 - 并且,至少如果有 SQL Server 2008 及更高版本,您使用 MERGE 语句更新 customer table:

MERGE customer t
USING stg_customer s
  ON t.custid = s. custid
WHEN MATCHED THEN UPDATE SET
  remarks = s.remarks
;