You can import the CSV file to a temporary table and from this temporary table make the inclusion in the definitive table using something like
-- código #1
declare @Ultimo int;
BEGIN TRANSACTION;
SELECT top (1) @Ultimo= id
from tabela with (tablockx)
order by id desc;
INSERT into tabela with (tablockx) (id, demais colunas)
SELECT @Ultimo + row_number() over (order by (SELECT 0)),
demais colunas
from #tabelatemp;
COMMIT;
It is a suggestion that you should evaluate whether the table lock is obtained or not.
You need to be aware of the growth of transaction log while the import is underway.
If you want the value generated for "id" to be in the order of a field in the CSV file, replace (SELECT 0)
by the name of the respective column in the temporary table.
It is possible to import directly from the text file to the table when replacing #tabelatemp
for OPENROWSET (BULK ...)
. Details in the article "Bulk import of data”.
Change the field type to IDENTITY and delete the column from the CSV file
– Reginaldo Rigo
"MAX(ID)+1" is a bad technique for generating keys. Details in the article Generation of numerical sequences -> https://portosql.wordpress.com/2019/04/21/geracao-de-sequencias-numericas/
– José Diz
The import is performed in a unique mode, that is, only by accessing the table? What is the approximate number of CSV file records?
– José Diz