Break string into rows tab delimited SQL Server

时间:2015-09-14 15:49:31

标签: sql sql-server string

I am attempting to write a function which splits a string form a .txt file (tab delimited) bulk inserted into a SQL Server table.

I have successfully run the procedure (with function) on a comma-delimited result from the bulk insert but can't seem to get it to successfully split the string into rows for tab-delimited. The result returns the string as a single row!

Would be great if someone could help out.

Here is the code for the function

ALTER FUNCTION dbo.BreakStringIntoRows (@CommadelimitedString varchar(1000))
RETURNS @Result TABLE (Headers VARCHAR(500))
AS
BEGIN
    DECLARE @IntLocation INT

    WHILE (CHARINDEX('\t', @CommadelimitedString, 0) > 0)
    BEGIN
          SET @IntLocation = CHARINDEX('\t', @CommadelimitedString, 0)      

          INSERT INTO @Result (Headers)
             --LTRIM and RTRIM to ensure blank spaces are removed
             SELECT RTRIM(LTRIM(SUBSTRING(@CommadelimitedString, 0, @IntLocation)))   

          SET @CommadelimitedString = STUFF(@CommadelimitedString, 1, @IntLocation, '') 
    END

    INSERT INTO @Result (Headers)
       SELECT RTRIM(LTRIM(@CommadelimitedString))  -- LTRIM and RTRIM to ensure blank spaces are removed
    RETURN 
END
GO

1 个答案:

答案 0 :(得分:0)

SQL Server中的

\ t没有转到选项卡,您需要实际使用选项卡,或者可能更清楚CHAR(9),因此最终可能会使用SET @IntLocation = CHARINDEX(CHAR(9),@ CommadelimitedString ,0) - GarethD