Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 Development Tools
 Other Development Tools
 Split the string into column

Author  Topic 

Varsha Patil
Starting Member

3 Posts

Posted - 2008-05-16 : 14:50:02
I have created one table in MS ACCESS with only one column.
The column field contain text format data i.e log string paste in single column (field).

String Eg : "329658 542896321 esalr 20 Ape 2008 20:29 315:329 itgto vpa015 f258697"

Now i want to split this long string into different column & store that all column in new table.

Eg: Col1 = 329658 & Col2 = 542896321 & so on

Please reply asap.
Thanks

Transact Charlie
Master Smack Fu Yak Hacker

3451 Posts

Posted - 2008-07-03 : 07:24:51
What about making a user defined function that will return a table given a string...

I stole this from somewhere on the net' ages ago so I can't give credit to whoever wrote it. It's very useful though.

It returns a table of values from your string based on the the delimiter you specify.

IF EXISTS (
SELECT * from dbo.sysobjects
WHERE
id = object_id(N'[dbo].[fn_Split]')
AND xtype IN (N'FN', N'IF', N'TF')
)
DROP FUNCTION [dbo].[fn_Split]
GO


CREATE FUNCTION fn_Split (@text VARCHAR(8000), @delimiter VARCHAR(20) = ' ')

RETURNS @Strings TABLE (
position INT IDENTITY PRIMARY KEY
, value VARCHAR(8000)
)

AS BEGIN
DECLARE @index int
SET @index = -1

WHILE (LEN(@text) > 0) BEGIN
-- Find the first delimiter
SET @index = CHARINDEX(@delimiter , @text)

-- No delimiter left?
-- Insert the remaining @text and break the loop
IF (@index = 0) AND (LEN(@text) > 0) BEGIN
INSERT INTO @Strings VALUES (@text)
BREAK
END

-- Found a delimiter
-- Insert left of the delimiter and truncate the @text
IF (@index > 1) BEGIN
INSERT INTO @Strings VALUES (LEFT(@text, @index - 1))
SET @text = RIGHT(@text, (LEN(@text) - @index))
END
-- Delimiter is 1st position = no @text to insert
ELSE SET @text = RIGHT(@text, (LEN(@text) - @index))
END
RETURN
END
GO


-------------
Charlie
Go to Top of Page

Transact Charlie
Master Smack Fu Yak Hacker

3451 Posts

Posted - 2008-07-03 : 07:26:39
And then, reading your requirement again, you would need to pivot the table to get your columns.



-------------
Charlie
Go to Top of Page
   

- Advertisement -