I have read a text file with the bulk syntax but after that I have found another problem: In my text file it has the same header and detail in it so my problem now is how can I put the header in a table1 and the detail in a table2?
Another thing I create just a field1 for put all my rows (header and detail), but they have FIELDTERMINATOR = ‘|’, but the header it has seven fields and the detail it has eleven fields so that’s another problem because I cannot create just one table with the exact fields to put my detail and header.
This an example of the text files I am reading:
HR|001580/06|RG|11/01/2013 12:00|BG|3573|001580
IT|001580/01|1|00147066||1200|852.3|830.3|1.35|UNIDAD|0|31/12/2014
00:00
IT|001580/02|1|00147066||200|852.3|830.3|1.35|UNIDAD|1|31/12/2014
00:00
IT|001580/03|1|00147066||100|852.3|830.3|1.35|UNIDAD|55|31/12/2014
00:00
IT|001580/04|2|00254276||200|852.3|830.3|1.35|UNIDAD|0|31/12/2014
00:00
IT|001580/05|3|00305359||1700|852.3|830.3|1.35|UNIDAD|0|31/12/2014
00:00
IT|001580/06|3|00305359||300|852.3|830.3|1.35|UNIDAD|1|31/12/2014
00:00
This is the query I have…
CREATE TABLE #temp
(
campo1 VARCHAR(max)
)
BULK INSERT #temp
FROM ”
WITH
(
FIELDTERMINATOR = ‘|’,
ROWTERMINATOR = ‘\n’
)
This firs query it is for the header
SELECT *
FROM #temp
WHERE SUBSTRING(campo1,1,2) = ‘HR’
This firs query it is for the detail
SELECT *
FROM #temp
WHERE SUBSTRING(campo1,1,2) = ‘IT’
How can I separate the fields for the header and the detail?
Thanks for the advice to Pondlife, i got the answer for my own question.
Here we go;
Well as we know i have this text file that in the same time has the header and the detail
So i need to:
For the First Step i create a table and then i use the Sql BulkInsert
i got something like this.
We see that the rows it has delimiters( | ), that means the fields of the each table (HR – Header, IT – Details)
Then for my second and third step i need insert the rows on each table, but also i need to separate each fields of each row, so i create a procedure that receive a string and delimiter and return a table with each field of my string, i created the fields dynamically.
If you want to create the procedure you need to run this first
SET QUOTED_IDENTIFIER OFFThen you can create it.
If you see i comment the three first lines for execute the procedure and you can get something like this
Well we not finish yet, we read the file, and we create the procedure that return the fields and now we need insert into each table, for that i create two temp table with static fields ’cause i know the fields of each table and then create Cursor for read each row on my #ImporData table.
After that if you put all the pieces on the same query you got this.
As i need to.
Again thanks Pondlife to give me the advice for the split.