0

I have been a curious , whether is this possible in SQL

Here is my table

Text
-----
India 01/01/2001 Mumbai
SriLanka 01/01/2001 Colombo
USA 01/01/2001 Chicago

From these create table separate columns (separated by space) like

Country     Date        Location  
-----       -----       -------- 
India       01/01/2001   Mumbai
SriLanka    01/01/2001   Colombo
USA         01/01/2001   Chicago

Only thing that structs me over here is regex that we do in JAVA.

Is something like possible in SQL as well.

Thanks !!!

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
user1141584
  • 619
  • 5
  • 16
  • 29

2 Answers2

1

You could split the columns with a table-valued function like this:

CREATE FUNCTION [dbo].[fnParseFields] ( @str NVARCHAR(max), @delimiter NCHAR )
RETURNS @retval TABLE(Country NVARCHAR(max), [Date] NVARCHAR(max), Location NVARCHAR(max))
AS
BEGIN
    declare @f1 varchar(max), @f2 varchar(max), @f3 varchar(max);
    set @str=ltrim(@str);

    -- Field 1
    set @f1=(left(@str,CHARINDEX(@delimiter,@str,1)-1));
    SET @str=RIGHT(@str,LEN(@str)-CHARINDEX(@delimiter,@str,1));

    -- Field 2
    set @f2=(left(@str,CHARINDEX(@delimiter,@str,1)-1));

    -- Field 3
    SET @f3=RIGHT(@str,LEN(@str)-CHARINDEX(@delimiter,@str,1));
    insert into @retval values (@f1,@f2,@f3);

    RETURN;
END

GO

create table myText (sometext varchar(80));

insert into myText values
('India 01/01/2001 Mumbai')
, ('SriLanka 01/01/2001 Colombo')
, ('USA 01/01/2001 Chicago');
go

select f.* from myText
cross apply [dbo].[fnParseFields](sometext,' ') f
go

Result:

enter image description here

John Dewey
  • 6,985
  • 3
  • 22
  • 26
0

Didn't actually try it yet, but it's possible to import a Comma Separated Value file using T-SQL

BULK
INSERT tableName
FROM 'c:\csvtest.txt'
WITH
(
FIELDTERMINATOR = ' ',
ROWTERMINATOR = '\n'
)

Here is the source for the sample.

Update If the data is stored in the database, there seems to be no simpler solution than to write a function/stored procedure to parse the CSV, something like this SO answer suggests.

Community
  • 1
  • 1
Călin Darie
  • 5,937
  • 1
  • 18
  • 13