Question

My database named 'dictionary' have two column named 'column1' and 'column2'. Both can accept NULL value. The data-type of both columns is INT. Now I want to insert into only column2 from a text file using bcp. I made a format file. My format file is like that

<?xml version="1.0"?>
  <BCPFORMAT xmlns="http://schemas.microsoft.com/sqlserver/2004/bulkload/format" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <RECORD>
      <FIELD ID="1" xsi:type="CharTerm" TERMINATOR="," MAX_LENGTH="7"/>
      <FIELD ID="2" xsi:type="CharTerm" TERMINATOR="\r\n" MAX_LENGTH="24"/>
     </RECORD>
      <ROW>
        <COLUMN SOURCE="1" NAME="column2" xsi:type="SQLINT"/>
      </ROW>
   </BCPFORMAT>

and my bulk statement is like

BULK INSERT dictionary
 FROM 'C:\Users\jka\Desktop\n.txt'
  WITH
  (
   FIELDTERMINATOR = '\n',
    ROWTERMINATOR = '\n',
   FORMATFILE = 'path to my format file.xml'
   ) 

But it didn't work? How can I solve this?

N:B: My txt file looks like

123 
456
4101

......

One more question Edited: i can fill one colum by this technique but when i fill another column from a text file like before from the 1st row. how can i do that ???

Was it helpful?

Solution

Assuming that your format file is correct I believe you need to ditch FIELDTERMINATOR and ROWTERMINATOR from your BULK INSERT

BULK INSERT dictionary
FROM 'C:\Users\jka\Desktop\n.txt'
WITH (FORMATFILE = 'path to my format file.xml') 

Also make sure that:

  1. input file's encoding is correct. In your case most likely it should be ANSI and not UTF-8 or Unicode.
  2. row terminator (which is second field terminator in your format file) is actually \r\n and not \n.

UPDATE Since you need to skip first column:

With an XML format file, there is no way to skip a column when you are importing directly into a table by using a BULK INSERT statement. In order to achieve desired result and still use XML format file you need to use OPENROWSET(BULK...) and provide explicit list of columns in the select list and in the target table.

So to insert data only to column2 use:

INSERT INTO dictionary(column2)
SELECT column2
  FROM OPENROWSET(BULK 'C:\temp\infile1.txt',
       FORMATFILE='C:\temp\bulkfmt.xml') as t1;

If your data file has only one field your format file can look like this

<?xml version="1.0"?>
<BCPFORMAT xmlns="http://schemas.microsoft.com/sqlserver/2004/bulkload/format" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <RECORD>
        <FIELD ID="C1" xsi:type="CharTerm" TERMINATOR="\r\n" MAX_LENGTH="24"/>
    </RECORD>
    <ROW>
        <COLUMN SOURCE="C1" NAME="column2" xsi:type="SQLINT"/>
    </ROW>
</BCPFORMAT>

OTHER TIPS

Your data file contains one field, so your format file should reflect that

<RECORD>
  <FIELD ID="1" xsi:type="CharTerm" TERMINATOR="\r\n"/>
</RECORD>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top