SQL server bulk insert delimited values into single column, split into columns then insert into another table

时间:2015-10-21 12:49:32

标签: sql-server sql-server-2012 cursor bulkinsert temp-tables

I have a #tmp table with a single field.

I have inserted values which look something like;

2015-01-01.124587.21654#I#U#my company#ltd#brown####day

They are '#' delimited and \r\n terminated.

I know, from what I am testing, I am unable to BULK insert from #tmp to my source table.

How can I quickly get at these fields?

I have a directory with 60 files that have headers and footers I don't want. Variable number of rows etc. So I have inserted them into a single field to avoid the continuing error I have been getting about unexpected end of file amongst others.

I have prepared a cursor to take in these files iteratively and remove head and tail then insert into their master table with correct headers. So far I am only at a temp table stage.

I have removed the rows which contain my headers and footers in the files. Now I need the columns into their correct table/fields.

Any pointers?

EDIT: Using the XML table valued function

ALTER FUNCTION [dbo].[SplitStrings_XML]
(
   @List       NVARCHAR(MAX),
   @Delimiter  NVARCHAR(255)
)
RETURNS TABLE
WITH SCHEMABINDING
AS
   RETURN 
   (  
      SELECT Item = y.i.value('(./text())[1]', 'nvarchar(4000)')
      FROM 
      ( 
        SELECT x = CONVERT(XML, '<i>' 
          + REPLACE(@List, @Delimiter, '</i><i>') 
          + '</i>').query('.')
      ) AS a CROSS APPLY x.nodes('i') AS y(i)
   );

How do I use this?

SELECT * FROM dbo.SplitStrings_XML(#tmp.Identifier, '#') 

??

    Msg 4104, Level 16, State 1, Line 48
The multi-part identifier "#tmp.Identifier" could not be bound.

1 个答案:

答案 0 :(得分:0)

我设法通过解决编码和行终止符错误来解决问题,因此不再需要拆分单个列。