views:

58

answers:

2

Hi all,

I have a query to split the data but it is based on a delimiter. My query is:

DECLARE @xml xml,@str varchar(100),@delimiter varchar(10)
SET @str= 'VINAYKUMAR,VINAYKUMAR,VINAYKUMAR,VINAYKUMAR,VINAYKUMAR,VINAYKUMAR,VINAYKUMAR'
SET @delimiter =','
SET @xml = cast(('<X>'+replace(@str,@delimiter ,'</X><X>')+'</X>') as xml)
select @xml
SELECT a.value('.','varchar(10)') as value FROM @xml.nodes('X') as X(a)

I want split the data based on length i.e 10 characters.

Thanks in advance.

+1  A: 

Use SUBSTRING

TFD
+1  A: 

Something like... (Edit: separator safe now)

DECLARE @str varchar(100)
DECLARE @splitlen tinyint, @hasSeparator bit;

SELECT @str= 'VINAYKUMAR,VINAYKUMAR,VINAYKUMAR,VINAYKUMAR,VINAYKUMAR,VINAYKUMAR,VINAYKUMAR'
SELECT @splitlen = 10, @hasSeparator = 1

;WITH cNumber AS 
(
    SELECT
        ROW_NUMBER() OVER (ORDER BY C1.column_id) * (@splitlen+@hasSeparator) - @splitlen + (1-@hasSeparator) AS Number
    FROM
        sys.columns C1, sys.columns C2
)
SELECT
    SUBSTRING(@str, Number, @splitlen-@hasSeparator)
FROM
    cNumber
WHERE
    Number < LEN (@str)



SELECT @str= 'VINAYKUMARVINAYKUMARVINAYKUMARVINAYKUMARVINAYKUMARVINAYKUMARVINAYKUMAR'
SELECT @splitlen = 10, @hasSeparator = 0
;WITH cNumber AS 
(
    SELECT
        ROW_NUMBER() OVER (ORDER BY C1.column_id) * (@splitlen+@hasSeparator) - @splitlen + (1-@hasSeparator) AS Number
    FROM
        sys.columns C1, sys.columns C2
)
SELECT
    SUBSTRING(@str, Number, @splitlen - @hasSeparator)
FROM
    cNumber
WHERE
    Number < LEN (@str)
gbn
when delimiter is present in data we can use the above... but i need to split the data based on the SIZE (i.e 10)@str= 'VINAYKUMARVINAYKUMARVINAYKUMARVINAYKUMARVINAYKUMARVINAYKUMARVINAYKUMAR'
VinnaKanna
@VinnaKanna: Your example did not mention that. My solution also is based on length but allows for
gbn
thank you very much.... But the problem in above query is taking more time....And can you explain any other way to get same with out sys.columns...But thank you dear
VinnaKanna
Create a basic numbers table instead
gbn