Skip to content

Instantly share code, notes, and snippets.

@yos-virtus
Last active April 23, 2017 05:28
Show Gist options
  • Save yos-virtus/0d1dde74f9f101c9a49aa587e980cfc7 to your computer and use it in GitHub Desktop.
Save yos-virtus/0d1dde74f9f101c9a49aa587e980cfc7 to your computer and use it in GitHub Desktop.
Update SQL Server table with csv data/Обновление данных таблицы SQL Server с помощью csv
IF OBJECT_ID('TempDB.dbo.#tmp_table', 'U') IS NULL
BEGIN
-- Create temp table if not it does not exest already / Создаем временную таблицу если ее еще нет
CREATE TABLE #tmp_table
(
field1 integer,
field2 varchar(255),
field3 varchar(255)
)
END
ELSE
BEGIN
-- If temporary table exist clean it / Очищаем временную таблицу если она существует
TRUNCATE TABLE #tmp_table
END
-- Fill temporary table with csv data / Заполняем временную таблицу данными из csv
BULK INSERT #tmp_table
FROM 'path_to_the_file'
WITH
(
CODEPAGE = 'RAW',
FIRSTROW = 2,
FIELDTERMINATOR = ';',
ROWTERMINATOR = '\n'
)
-- Update target table with data from csv / Обновляем целевую таблицу данными из csv
UPDATE real_table
SET real_table.field2 = #tmp_table.field2
,real_table.field3 = #tmp_table.field3
FROM #tmp_table
WHERE real_table.id = #tmp_table.field1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment