The only way to do this would be to open the file with something else (Powershell script, VBS, C#/VB.net, etc.) and check the first line, passing back a result to indicate how many columns it found. There is nothing in SQL Server that will do this for you (short of loading the whole file as a single-column table).
Conditional BULK INSERT for CSV files with different number of columns in SQL Server
-
31-05-2022 - |
Question
I've generated a BCP FORMAT FILE (xml) for importing a CSV file into a SQL SERVER table. There are 100+ CSV files (representing IIS web logs). Some sites collect 5 columns of data, and some sites collect 6 columns of data. The first five columns are the same.
Is there anyway I can check first how many columns the CSV file has BEFORE I do the BULK INSERT command? That way, I can choose the correct format file to use with the command without getting an error stating columns are missing.
Solution
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow