sqlsql-serversql-server-2008t-sqlssms

Convert varchar list to int in Sql Server


I need a way to have the @listOfPageIds be recognized as a list of numbers instead of strings. I have tried casting, removing the single quotes... I really don't want to do a loop in sql.

Declare @listOfPageIds varchar(50) ;

Set @listofPageIds = '2, 3, 4, 5, 6, 7, 14, 15';

select * from mytable p where p.PageId in( @listOfPageIds);

Solution

  • Well on production server I'd write some table valued function for splitting lists, but if you need quick ad-hoc query, this xml trick could work

    declare @listOfPageIds varchar(50), @data xml
    declare @temp table(id int)
    
    select @listofPageIds = '2, 3, 4, 5, 6, 7, 14, 15';
    select @data = '<t>' + replace(@listofPageIds, ', ', '</t><t>') + '</t>'
    
    insert into @temp
    select
        t.c.value('.', 'int') as id
    from @data.nodes('t') as t(c)
    
    select * from @temp
    

    sql fiddle demo