Friday, May 8, 2009

Sql function to Convert VARCHAR to INT

To Convert the value from varchar to int I created a small function as shown below:

Create Function [dbo].[CsvToInt] ( @Array varchar(1000)) returns @IntTable table (IntValue int)ASbegin
declare @separator char(1) set @separator = ','
declare @separator_position int declare @array_value varchar(1000) set @array = @array + ',' while patindex('%,%' , @array) <> 0 begin select @separator_position = patindex('%,%' , @array) select @array_value = left(@array, @separator_position - 1) Insert @IntTable Values (Cast(@array_value as int))
select @array = stuff(@array, 1, @separator_position, '') end
return end

1 comment:

public key infrastructure said...

I am searching for Sql function to Convert VARCHAR to INT but unable to understand the logic you used in the blog.Can you please explain it a bit so that it can be easy for me to understand.It will really help me.Thanks!