How to add inline TVF with dynamic columns from CRL Dynamic Pivot

Hi I am trying to implement the code in the following article.

SQLServerCentral Article

Now, I've pushed the assembly to my DB and can see it there.
So far I have tried building an Inline TVF, as I assume this is how it would be used on the DB; however, I am receiving the following error on my code, I must be missing a step somewhere, as I've never done this before. I'm lost on how to implement this clr function on my db?

Create Function script:

CREATE FUNCTION clrDynamicPivot
(	
	-- Add the parameters for the function here
	@query nvarchar(4000),
	@pivotColumn nvarchar(4000),
	@selectCols nvarchar(4000),
	@aggCols nvarchar(4000),
	@orderBy nvarchar(4000)	
)
RETURNS TABLE 
AS
return
	 (external NAME CLRfunctions.RIFunctions.clrDynamicPivot)

Open in new window


Error message:

Msg 156, Level 15, State 1, Procedure clrDynamicPivot, Line 18
Incorrect syntax near the keyword 'external'.

Open in new window


CLR Code:

public static void CreateTempTable(SqlString query)
        {
            using (SqlConnection sqlconn = new SqlConnection("Context Connection=True"))
            {
                SqlCommand sqlCmd = sqlconn.CreateCommand();
                sqlCmd.CommandText = query.ToString();
                sqlconn.Open();
                sqlCmd.ExecuteNonQuery();
            }
        }

public static string GetPivotData(string pivotColumn)
        {
            string stmt = string.Format("select distinct {0} from #temp", pivotColumn);
            string pivotCols = string.Empty;
 
            using (SqlConnection cn = new SqlConnection("Context Connection=True"))
            {
                SqlCommand cmd = cn.CreateCommand();
                cmd.CommandText = stmt;
                cn.Open();
                using (SqlDataReader dr = cmd.ExecuteReader())
                {
                    while (dr.Read())
                    {
                        if (dr.GetFieldType(0) == typeof(System.Int32))
                            pivotCols += "[" + dr.GetInt32(0) + "],";
                        if (dr.GetFieldType(0) == typeof(System.Decimal))
                            pivotCols += "[" + dr.GetDecimal(0) + "],";
                        if (dr.GetFieldType(0) == typeof(System.String))
                            pivotCols += "[" + dr.GetString(0) + "],";
                    }
                }
            }
            return pivotCols.Remove(pivotCols.Length - 1);

public static void clrDynamicPivot(SqlString query, SqlString pivotColumn, SqlString selectCols, SqlString aggCols, SqlString orderBy)
   {
    string stmt = string.Empty;
    try
     {
       CreateTempTable(query);
       string pivot = GetPivotData(pivotColumn.ToString());
       stmt = string.Format("select * from ( select {0} from #temp ) as t pivot ( {1} for {2} in ( {3} )) as p {4}",
       selectCols.ToString(),
       aggCols.ToString(),
       pivotColumn.ToString(),
       pivot,
       orderBy.ToString());
       using (SqlConnection cn = new SqlConnection("Context Connection=True"))
         {
          SqlCommand cmd = cn.CreateCommand();
          cmd.CommandText = stmt;
          cn.Open();
          SqlDataReader reader = cmd.ExecuteReader();
          SqlContext.Pipe.Send(reader);
         }
 
      }
     catch (Exception ex)
      {
       throw new Exception(string.Format("clrDynamicPivot Error stmt:{0}", stmt), ex);
      }
 }

Open in new window


Call to the stored procedure:

DECLARE @query nvarchar(4000)
DECLARE @pivotColumn nvarchar(4000)
DECLARE @selectCols nvarchar(4000)
DECLARE @aggCols nvarchar(4000)
DECLARE @orderBy nvarchar(4000)

set @query = 'select PayMethod, datepart(hh, OrderDate) as OrderHour, ProductTotal into #temp from dbo.Orders (nolock) where OrderDate between getdate()-1 and getdate() and division = ''15'''

set @pivotColumn = 'PayMethod'
set @selectCols = 'PayMethod, OrderHour, ProductTotal'
set @aggCols = 'sum(ProductTotal)'
set @orderBy = ''

EXECUTE dbo.clrDynamicPivot
   @query
  ,@pivotColumn
  ,@selectCols
  ,@aggCols
  ,@orderBy
GO

Open in new window

Scarlett72Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Vitor MontalvãoMSSQL Senior EngineerCommented:
I can't help you much here because I'm not expert on CLR but by the CREATE FUNCTION statement you have is wrong. There's 2 returns and you only need the first one:
CREATE FUNCTION clrDynamicPivot
(	
	-- Add the parameters for the function here
	@query nvarchar(4000),
	@pivotColumn nvarchar(4000),
	@selectCols nvarchar(4000),
	@aggCols nvarchar(4000),
	@orderBy nvarchar(4000)	
)
RETURNS TABLE 
AS
	 external NAME CLRfunctions.RIFunctions.clrDynamicPivot

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server 2008

From novice to tech pro — start learning today.