Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bulk Insert into SQL Server from text file adding a uniqueidentifier, or skipping a column

I need to take rows from a text file and insert into a table. The rows of the file are similar to the following:

string1
string2
string3
string4
...

My table has 2 columns:

uniqueidentifier, stringValue

I would like to do a bulk insert into the table grabbing each row from the text file and adding a new uniqueidentifier to each one (ideally a GUID, but an integer counter would be fine).

Anyone have a tip on how to do this bulk upload? So far my SQL is:

BULK
INSERT tableNameToInsertInto
FROM 'C:\importList.txt'
WITH
(
ROWTERMINATOR = '\n'
)
GO
like image 642
ter24 Avatar asked Sep 08 '26 04:09

ter24


1 Answers

Try this one -

Values:

C:\importList.txt ->
string1
string2
string3
string4

Format file:

C:\importList.fmt ->
11.0
1
1     SQLCHAR     0     100     "\r\n"     1     text     ""

Query:

CREATE TABLE dbo.testBulk 
(
      RowUID UNIQUEIDENTIFIER DEFAULT NEWID()
    , Value VARCHAR(100)
)

INSERT INTO dbo.testBulk (Value)
SELECT c.[text]
FROM OPENROWSET(
    BULK N'C:\importList.txt', 
    FORMATFILE = 'C:\importList.fmt'
) c
like image 123
Devart Avatar answered Sep 09 '26 17:09

Devart



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!