title: SQL Server 2008R2 Custom Function so slow
body: <p>Here is my function:</p>
  
  <pre><code>-- DECLARE @cur CURSOR
  DECLARE @line int
  declare @return varchar(255)
  
  DECLARE myCursor CURSOR FOR
  SELECT DISTINCT (quote_ln_no) as quote_ln_no
    FROM dbo.quote_line_bom
   WHERE quote_no = @quote_no AND component_mat_no = @mat_no
  ORDER BY quote_ln_no
  
  set @return = ''
  
  OPEN myCursor
  
  FETCH NEXT FROM myCursor
  INTO @line
  WHILE @@FETCH_STATUS = 0
  BEGIN
    set @return = @return + convert(varchar, @line) + ', '
    FETCH NEXT FROM myCursor 
    INTO @line
  END
  
  CLOSE myCursor
  DEALLOCATE myCursor 
  
  if len(@return) &gt; 0 
  set @return = substring(@return, 1, len(@return)-1)
  
  return @return
  </code></pre>
  
  <p>When I use this function in a query which returns over 3000 records, function adds 20 seconds.</p>
  
  <p>Please let me know what is wrong with it or is there a way to make it run faster?</p>