The rows from the file are read in order, and added to the table in the same order.
The issue occurs when you read rows from the table. Without an
ORDER BY clause on your
SELECT, SQL Server is free to return rows from the table in whatever order is convenient.
The question doesn't provide a definition for the table
##AllRows, but it seems certain the table is a heap (a table without a clustered index). SQL Server reads pages from a heap using Index Allocation Map (IAM) structures. This means data tends to be returned in file and page id order within each IAM chain, which will generally not reflect the order in which data was inserted. This is the underlying cause of the behaviour you are seeing.
You need a column to indicate the order of rows in the file, then order by that column when you write your query. Unfortunately, SQL Server does not provide a built-in way to add this 'sequence' column during import.
There are a couple of common workarounds:
- Pre-process the source file outside SQL Server to add a sequence number to each row. This is the most reliable method.
- Assign a sequence number during the import.
The second method carries some risk because there is no documented guarantee that this will work reliably in all circumstances. Nevertheless, people have been using this idea successfully for a long time. The general idea is:
- Add an
IDENTITY column to the import table.
- Create a view over the import table, omitting the
BULK INSERT into the view.
This will not work with a global temporary table, because a view cannot reference that type of table. You would need to use a regular table (perhaps in tempdb) instead.
I used the following script to successfully import a csv file containing the Complete Works of Shakespeare:
The first step is to create a table in tempdb with an extra
CREATE TABLE dbo.Test
id integer IDENTITY PRIMARY KEY,
line nvarchar(4000) NOT NULL
Now we create a view over that table, omitting the
CREATE VIEW dbo.ImportTest
FROM dbo.Test AS T;
Finally, we bulk insert into the view:
BULK INSERT dbo.ImportTest
CODEPAGE = '65001',
DATAFILETYPE = 'char',
ROWTERMINATOR = '\n'
We can now see the first few lines in file order using a
SELECT TOP (20)
FROM dbo.Test AS T
The result shows the text in the right order:
It is also possible to use
OPENROWSET with a format file. Using the same example csv file, I was able to import the data using the following format file (saved as
<BCPFORMAT xmlns="http://schemas.microsoft.com/sqlserver/2004/bulkload/format" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<FIELD ID="1" xsi:type="CharTerm" TERMINATOR="\r\n"/>
<COLUMN SOURCE="1" NAME="line" xsi:type="SQLNVARCHAR" NULLABLE="NO"/>
FORMATFILE = 'C:\Temp\shakespeare.xml',
CODEPAGE = '65001'
) AS ORO;
Notice that this method does not require a view, so you could target a global temporary table. The target table still needs the extra