简体   繁体   English

使用CSV更新预先存在的SQL Server表中的记录

[英]Using CSV to update records in pre-exisiting SQL Server table

My SQL Server 2012 table is CUST_TABLE . 我的SQL Server 2012表为CUST_TABLE It already has a lot of customer records (more than 10,000). 它已经有很多客户记录(超过10,000个)。

I have a CSV with the first column customer number which is my primary key. 我有一个带有第一列客户编号的CSV,这是我的主键。 The second column has email addresses. 第二列包含电子邮件地址。 The first row of this CSV contains columns heading custnum and email. 此CSV的第一行包含标题为custnum和email的列。 The CSV has 125 data rows. CSV具有125个数据行。 I am using SSMS and want to update just 125 customer records and change their email. 我正在使用SSMS,只想更新125个客户记录并更改他们的电子邮件。

The only solution I found was to have update statements to change the data. 我发现的唯一解决方案是使用更新语句来更改数据。 Is there any other easier way to do this? 还有其他更简单的方法吗? Like using the import data function by right-clicking on the database and then hovering over tasks. 就像通过右键单击数据库,然后将鼠标悬停在任务上来使用导入数据功能一样。 Thank you. 谢谢。

Read the csv into a temp table, then update your table using the temp table. 将csv读取到临时表中,然后使用临时表更新表。

For example: 例如:

USE yourdb;

GO

IF OBJECT_ID('tempdb.dbo.#tmp', 'U') IS NOT NULL
    DROP TABLE #tmp;

GO

CREATE TABLE #tmp (
    t_cust_nr   NVARCHAR(MAX),
    t_email     NVARCHAR(MAX)
)

SET NOCOUNT ON;

-- Read the csv, skip the first row
BULK INSERT #tmp 
    FROM 'C:\path\to\your.csv' 
    WITH (FIRSTROW = 2, FIELDTERMINATOR = ',', ROWTERMINATOR ='\n');

-- Trim whitespace
UPDATE #tmp
    SET t_cust_nr = LTRIM(RTRIM(t_cust_nr)),
        t_email = LTRIM(RTRIM(t_email));


-- Add your update statement here... 
-- You also might have to cast the t_cust_nr to a diff. data type if needed.


SET NOCOUNT OFF;

DROP TABLE #tmp;

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

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