Hi @Fabio Coatis ,
Thanks for providing a minimal reproducible example.
I tried to use it as-is, and got the following error:
Msg 4864, Level 16, State 1, Line 21
Bulk load data conversion error (type mismatch or invalid character for the specified codepage) for row 1, column 9 (NR_COTST).
I checked your source file, and noticed that its first row contains column headers.
So, I just slightly modified the T-SQL by adding FIRSTROW = 2 in comparison with the stackoverflow solution.
And it worked without any problem.
SQL
USE tempdb;
GO
DROP TABLE IF EXISTS dbo.Hist;
CREATE TABLE dbo.Hist
(
CNPJ_ID INT IDENTITY(1,1) PRIMARY KEY,
TP_FUNDO text NULL,
CNPJ_FUNDO nvarchar(max) NULL,
DT_COMPTC varchar(50) NOT NULL,
VL_TOTAL varchar(50) NOT NULL,
VL_QUOTA varchar(50) NOT NULL,
VL_PATRIM_LIQ varchar(50) NOT NULL,
CAPTC_DIA varchar(50) NOT NULL,
RESG_DIA varchar(50) NOT NULL,
NR_COTST int NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY];
INSERT INTO dbo.Hist (TP_FUNDO, CNPJ_FUNDO, DT_COMPTC, VL_TOTAL, VL_QUOTA, VL_PATRIM_LIQ, CAPTC_DIA, RESG_DIA, NR_COTST)
SELECT *
FROM OPENROWSET(
BULK 'e:\Temp\FabioCoatis-0345\2022.csv',
FORMATFILE = 'e:\Temp\FabioCoatis-0345\hist_format_file.xml',
FIRSTROW = 2
) AS t;
-- review results
SELECT * FROM dbo.Hist;
Please see below.
P.S. Please connect with me on LinkedIn.