How to convert sql varchar to sql int list

by iatanasov 29. January 2008 18:51
DECLARE @TEST VARCHAR(30)
SET @TEST = '1,2,3,47, 89, 67'
DECLARE @Current INT


DECLARE @LISTINT TABLE (Number INT)

WHILE (LEN(@TEST) > 0)
BEGIN
    IF (Charindex(',', @TEST) > 0)
    BEGIN
        SET @Current = LEFT(@TEST, Charindex(',', @TEST) - 1)
        
        SET @TEST = RIGHT(@TEST, LEN(@TEST) - Charindex(',', @TEST))
        
    END
    ELSE
    BEGIN
        SET @Current = CAST(@TEST AS INT)
        SET @TEST = NULL
    END

    INSERT INTO @LISTINT VALUES(@Current)
    SET @Current = NULL
END

SELECT Number
FROM @LISTINT

Currently rated 4.3 by 3 people

  • Currently 4.333333/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

MS SQL

Related posts

Comments

February 5. 2008 14:50

Gravatar

is there have a faster way than this?

mark us

February 23. 2008 17:14

Gravatar

yes have. you can use sqlclr function, include your assembly and reference this function while create db function

Ivan Atanasov

Add comment


(Will show your Gravatar icon)  

  Country flag




Live preview

July 6. 2008 05:30

Gravatar

Powered by BlogEngine.NET 1.1.0.7
Theme by Mads Kristensen

About the author

Ivan Atanasov - web developer
E-mail me Send mail Subscribe Feed

Calendar

<<  July 2008  >>
MoTuWeThFrSaSu
30123456
78910111213
14151617181920
21222324252627
28293031123
45678910

View posts in large calendar

Pages

    Recent posts

    Recent comments

    Authors

    Disclaimer

    The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

    © Copyright 2008 it-coder.com

    Sign in