title: Error using the export data option in SQL Server 2008 with function
body: <p>This is probably an easy question to answer, but I can't figure it out. </p>
  
  <p>I have this query which I want to export to Excel. I followed instructions detailed <a href="http://helpdeskgeek.com/how-to/export-sql-data-to-excel/" rel="nofollow">here</a>, but the sql query is not right because of the use of a function I defined earlier.</p>
  
  <p>This is the function I defined:</p>
  
  <pre><code>CREATE FUNCTION FullMonthsSeparation 
  (
      @DateA DATETIME,
      @DateB DATETIME
  )
  
  RETURNS INT
  AS
  BEGIN
  DECLARE @Result INT
  
  DECLARE @DateX DATETIME
  DECLARE @DateY DATETIME
  
  IF(@DateA &lt; @DateB)
  BEGIN
      SET @DateX = @DateA
      SET @DateY = @DateB
  END
  ELSE
  BEGIN
      SET @DateX = @DateB
      SET @DateY = @DateA
  END
  
  SET @Result = (
      SELECT 
      CASE 
          WHEN DATEPART(DAY, @DateX) &gt; DATEPART(DAY, @DateY)
              THEN DATEDIFF(MONTH, @DateX, @DateY) - 1
          ELSE DATEDIFF(MONTH, @DateX, @DateY)
      END
  )
  RETURN @Result
  END
  GO
  </code></pre>
  
  <p>This is the SQL Query that I want to export to Excel:</p>
  
  <pre><code>SELECT DISTINCT soc.idSocio,
                  (SELECT Count(*)
                   FROM   [BaseSR].[dbo].[Movimiento] m
                   WHERE  m.idSocio = soc.idSocio
                          AND m.TipoMovimiento = 1) AS CantidadDeCompras,
                  nombre,
                  (SELECT TOP 1 fecha
                   FROM   [BaseSR].[dbo].[Movimiento] m
                   WHERE  m.idSocio = soc.idSocio
                          AND m.TipoMovimiento = 1/*Consumos*/
                   ORDER  BY fecha DESC) AS UltimoMovimiento,
                  dbo.Fullmonthsseparation(soc.fechaAlta, Getdate()) AS MesesDesdeAltaEnPrograma
  FROM   [BaseSR].[dbo].[Socio] soc
  WHERE  soc.idTarjeta LIKE '2001%'
  </code></pre>
  
  <p>And this is the error message I get:</p>
  
  <blockquote>
    <p>The statement could not be parsed. Additional information: Deferred
    prepare could not be completed. Statement(s) could not be prepared.
    Cannot find either column "dbo" or the user-defined function or
    aggregate "dbo.FullMonthsSeparation", or the name is ambiguous.</p>
  </blockquote>
  
  <p>However, when I execute the query it runs without any problem. </p>
  
  <p>If I changed the sql query to <code>[BaseSR].dbo.FullMonthsSeparation(...</code> then the error is:</p>
  
  <blockquote>
    <p>The statement could not be parsed. Additional information: Deferred
    prepare could not be completed. Statement(s) could not be prepared.
    Cannot find either column "BaseSR" or the user-defined function or
    aggregate "BaseSR.dbo.FullMonthsSeparation", or the name is ambiguous.</p>
  </blockquote>
  
  <p>Any ideas?</p>