T-SQL How to convert comma separated string of numbers to integer

前端 未结 3 2048
挽巷
挽巷 2020-12-21 05:07

I get the error \"Conversion failed when converting the nvarchar value \'23,24,3,45,91,\' to data type int.\" The error seems to be occuring on the ON clause. E.ID is an int

3条回答
  •  青春惊慌失措
    2020-12-21 06:06

    Using xml datatype, you can explode your string to integers like this. Good candidate for a user defined function I would say :-)

    declare @test varchar(max)
    
    set @test = '1,2,3,4,5'
    
    select 
         T2.item.value('(./text())[1]','int') 
    from
         (select convert(xml,''+replace(@test,',','')+'') as xmldoc)
    as xmltable
         CROSS APPLY xmltable.xmldoc.nodes('/items/t') as T2(item) 
    

提交回复
热议问题