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 Aricle
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
@query nvarchar(4000),
@pivotColumn nvarchar(4000),
@selectCols nvarchar(4000),
@aggCols nvarchar(4000),
@orderBy nvarchar(4000)
RETURNS TABLE
AS
return
(external NAME CLRfunctions.RIFunctions.clrDynamicPivot)
GO
Error:
Msg 156, Level 15, State 1, Procedure clrDynamicPivot, Line 18
Incorrect syntax near the keyword 'external'.
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);
[Microsoft.SqlServer.Server.SqlProcedure(Name="clrDynamicPivot")]
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);
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

You can't build an inline TVF in SQLCLR, only (the equivalent of) multi-statement TVFs and scalar functions. And the SQLCLR code for multi-statement TVFs must be coded with a specific pattern, see
https://msdn.microsoft.com/en-us/library/ms131103.aspx.
Looking at the example you reference, it was implemented as a SQLCLR stored procedure.
Cheers, Bob
  

Similar Messages

  • How to add Excise item with out chapter id

    Dear all,
    How to add Excise item with out chapter id?
    Chapter id of purchae items will be known only after receiving Invoice/gate pass/delivery  chalan from supplier/vendor
    To send a purchase order we need to create that particular item in the master, but with out assigning chapter id system is  not allowing to save without chapter id.
    How to solve this?
    I am with SAP 8.8 and PL 10
    Thanks in advance
    regards,
    Kumar

    Hi Kumar,
    Refer the book of chapter ID or find out on internet you will get the chapter ID.
    Still if you not able to get  the chapter id then consult with excise advisory.
    But you can add Excise PO until you have the excise details in Item master.
    Regards,
    Datta Kharat

  • How to add a tip to flexfield columns

    How to add shorttip to Flex: (BankDetails) columns/segments. I know how to add shortip if it is a messtext input, I would like to know is there a way to add shorttip to Flexfield columns using personalizations.

    There seems to be no way for adding tip for a single segment using personalization.
    FYI:
    1. For whole region you can add a tip by creating a tip item just under flex item.
    2. Using controller, get the handle of any single segment. Then use the below method:
    oamessagetextinputbean.setLongTip()
    -Anand

  • How to get ALV Display with First column alone in sort

    How to get ALV Display with First column alone in sort

    HI,
    You can build Internal Table and send this to the parameter "IT_SORT".
    eg:
    "the sorting Internal Table structure is as whown below.
    DATA:  t_sort_info type slis_t_sortinfo_alv.
    "Build the Sort Internal Table
      t_sort_info-fieldname = 'CARRID'.
      t_sort_info-subtot = 'X'.
      append t_sort_info.
      t_sort_info-fieldname = 'FLDATE'.
      t_sort_info-subtot = 'X'.
      append t_sort_info.
    Then pass this "IT_SORT_INFO" table to the Function module "Reuse_alv_*". (Note send the body of the Internal table only like "<b>IT_SORT = IT_SORT_INFO[]</b>".
    Here i am making ALV output sorted on CARRID & FLDATE.
    You can specify only the First Column name for sorting.
    Regards,
    Manju
    Message was edited by:
            MANJUNATHA KS

  • Need detailed procedure on how to add an item with Item Style Check Box in

    Need detailed procedure on how to add an item with Item Style Check Box in Framework.

    The view instance should be the same as the view instance (view object) specified for your region.
    If the View Attribute already that you need already exists in the View Object then you can use it.
    Otherwise you have to extend the View Object and add the new attribute to it.
    --Prasanna                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • How do i send emails with outlook express from firefox

    how do i send emails with outlook express from firefox

    You can add a button by using the [http://webdesigns.ms11.net/getmail.html Get Mail] add-on.

  • How to send a mail with HTML body from Oracle

    Hi Team,
    Can somebody guide me how to send a mail with HTML body from oracle.
    Here is the piece of code i am trying to send a mail.
    procedure SEND_MAIL is
    cursor c_1 is select * from table_name;
    l_mail_id varchar2(40);
    -- ls_mailhost VARCHAR2(64) := Mailhost;
    ls_from VARCHAR2(64) := ‘[email protected]
    ls_subject VARCHAR2(200);
    ls_to VARCHAR2(64);
    l_mail_conn UTL_SMTP.connection;
    ls_left_menu_name VARCHAR2(64);
    ll_emp_num number(8);
    begin
    for i in c_1 loop
    begin
    l_mail_conn := UTL_SMTP.OPEN_CONNECTION('IP');
    UTL_SMTP.HELO(l_mail_conn, 'IP');
    UTL_SMTP.MAIL(l_mail_conn, LS_FROM);
    UTL_SMTP.RCPT(L_mail_conn, LS_TO);
    UTL_SMTP.DATA(l_mail_conn,'From: ' ||ls_from || utl_tcp.crlf ||
    'To: ' ||ls_to || utl_tcp.crlf ||
    'Subject: ' ||ls_subject|| utl_tcp.crlf);
    UTL_SMTP.QUIT(l_mail_conn);
    exception
    when no_data_found then
    null;
    when others then
    RAISE_APPLICATION_ERROR(-20000, 'Failed to send mail due to the following error: ' || sqlerrm);
    end;
    end loop;
    end;
    Thnx

    Hi Nicolas!
    Have you tried to set "Output Format" for "RAW Text" to HTM in SCOT.
    If HTM is missing in your dropdown-list, you could check out table SXCONVERT2. Copy the line with category T/format TXT, and change the format from TXT to HTM. The existing function
    SX_OBJECT_CONVERT__T.TXT does not need to be changed. Now you should be able to choose HTM in SCOT. You will probably need som HTML-tags in your text to make it look good.
    Hope this helps!
    Regards
    Geir

  • How do I transfer Fish with attitude game from IPad 2 to Ipad Air

    How do I transfer Fish with /attitude game from IPad 2 to Ipad Air

    Assuming you own both iPads (and are using the same Apple ID on both), simply sync your iPad 2 using iTunes, then sync your iPad Air using the same iTunes on your computer.

  • How to create a dynamic RTF report which creates dynamic columns based on dynamic column selection from a table?

    Hi All,
    Suppose I have table, whose structure changes frequently on daily basis.
    For eg. desc my_table gives you following column name on Day 1
    SQL > desc my_table;
    Output
    Name
    Age
    Phone
    On Day 2, two more columns are added, viz, Address and Salary.
    SQL > desc my_table;
    Output
    Name
    Age
    Phone
    Address
    Salary
    Now I want to create an Dynnamic RTF report which would fetch data from ALL columns from my_table on daily basis. For that I have defined a concurrent program with XML as output type and have attached a data template/data definition to it which takes in XML as input and gives final output of conc program in EXCEL layout. I am able to do this for constant number of columns, but dont know how to do it when the number of columns to be displayed changes dynamically.
    For Day 1 my XML file should be like this.
    <?xml version="1.0" encoding="UTF-8"?>
    <dataTemplate name="XYZ" description="iExpenses Report" Version="1.0">
    <dataQuery>
    <sqlStatement name="Q2">
    <![CDATA[
    SELECT Name
    ,Age
    ,Phone
    FROM my_table
    ]]>
    </sqlStatement>
    </dataQuery>
    <dataStructure>
    <group name="G_my_table" source="Q2">
      <element name="Name" value="Name" />
      <element name="Age" value="Age" />
      <element name="Phone" value="Phone" />
    </group>
    </dataStructure>
    </dataTemplate>
    And my Day 1, EXCEL output from RTF template should be like this.
    Name     Age     Phone
    Swapnill     23     12345
    For Day 2 my XML file should be like this. With 2 new columns selected in SELECT clause.
    <?xml version="1.0" encoding="UTF-8"?>
    <dataTemplate name="XYZ" description="iExpenses Report" Version="1.0">
    <dataQuery>
    <sqlStatement name="Q2">
    <![CDATA[
    SELECT Name
    ,Age
    ,Phone
    ,Address
    ,Salary
    FROM my_table
    ]]>
    </sqlStatement>
    </dataQuery>
    <dataStructure>
    <group name="G_my_table" source="Q2">
      <element name="Name" value="Name" />
      <element name="Age" value="Age" />
      <element name="Phone" value="Phone" />
      <element name="Address" value="Address" />
      <element name="Salary" value="Salary" />
    </group>
    </dataStructure>
    </dataTemplate>
    And my Day 2, EXCEL output from RTF template should be like this.
    Name     Age     Phone     Address     Salary
    Swapnill     23     12345         Madrid     100000
    Now, I dont know below things.
    Make the XML dynamic as in on Day 1 there must be 3 columns in the SELECT statement and on Day 2, 5 columns. I want to create one dynamic XML which should not be required to be changed if new columns are added in my_table. I dont know how to create this query and also create their corresponding elements below.
    Make the RTF template dyanamic as in Day1 there must 3 columns in EXCEL output and on Day 2, 5 columns. I want to create a Dynamic RTF template which would show all the columns selected in Dynamic XML.I dont know how the RTF will create new XML tags and how it will know where to place it in the report. Means, I can create RTF template on Day 1, by loading XML data for 3 columns and placing 3 XML tags in template. But how will it create and place tags for new columns on Day 2?
    Hope, you got my requirement, its a challenging one. Please let me know how I can implement the required solution using RTF dynamically without any manual intervention.
    Regards,
    Swapnil K.
    Message was edited by: SwapnilK

    Hi All,
    I am able to fulfil above requirement. Now I am stuck at below point. Need your help!
    Is there any way to UPDATE the XML file attached to a Data Definition (XML Publisher > Data Definition) using a standard package or procedure call or may be an API from backend? I am creating an XML dynamically and I want to attach it to its Data Definition programmatically using SQL.
    Please let me know if there is any oracle functionality to do this.
    If not, please let me know the standard directories on application/database server where the XML files attached to Data Definitions are stored.
    For eg, /$APPL_TOP/ar/1.0/sql or something.
    Regards,
    Swapnil K.

  • How to create a table with editable column values.

    Hi everyone,
    I think this is very simple but i'm not able to find how to do this. This is my requirement. I need to create a table with n columns and 1 row initially. user should be able to enter data into this table and click of a button should insert data into the data base table. Also there should be a button at the bottom of the table to add 1 row to the table.
    I know how to do the insert to database, but can anyone please let me know how to create a table that allows user to enter data and how to create a add 1 row button?
    Thanks in Advance!

    Raghu,
    Go through the ToolBox tutorial Create Page & Advanced table section of OAF Guide.
    Step 1 - You require to create EO & a VO based on this EO. This EO will be of DataBase table where you want to insert the data.
    Step 2 - Create a Advanced table region. (Refer this Adavanced table section for more on this)
    Step 3 - Attach this VO in the BC4J component of Adavanced Table region.
    Regards,
    Gyan

  • How to add a Link with children in the SuiteLink bar?

    Hello,
    I have developed a code to add a new link in the SuiteLink bar using delegate control that works as expected. Now I want to include a new link
    but with children, I have tried many options in my code but with not luck.
    What I need in the SuiteLink bar is something like:
    My Services   Newsfeed  OneDrive  Sites
        Service 1
        Service 2
        Service 3
    Any idea on how to achieve this?
    Thanks,
    Daniel
    Daniel Villacis

    Hi,
    According to your post, my understanding is that you want to add sublink in the top navigation bar.
    There is an article about this issue, it contains the steps about how to create a link with sublink in the top navigation bar, you can have a look at it.
    http://www.helpmeonsharepoint.com/2012/03/custom-sharepoint-top-menu-and.html
    Thanks,
    Jason
    Forum Support
    Please remember to mark the replies as answers if they help and unmark them if they provide no help. If you have feedback for TechNet Subscriber Support, contact
    [email protected]
    Jason Guo
    TechNet Community Support

  • Adobe Reader - how to add page numbers with the free version?

    Hey guys,
    Imagine I've got a PDF file and I want to create a new one by selecting some pages out of it. I know this is simply possible by using the PDFcreator but I want to add page numbers. As far as I know this is not possible with the free version of Adobe unless I would add the page number on every single page by using a text box. I want to make different catalogs from the PDF so the page numbers are really necessary. Have you got any idea how to solve that issue? You know that's pretty much the only thing I need to add which means it's not worth buying the Pro version. Unfortunately I only got the PDF and I can't work on it e.g. with MS word before I export it. Do you know if there is a way to add page numbers with a free version? There might be an additional free software which allows that?
    Thanks for your support! 

    Thanks for your quick replies.
    I know how to add text page by page. But obviously it's hard to place the numbers on the very same position, is it?

  • How to take list backup with lookup columns data in sharepoint 2010

    Hi friends,
    I have one issue on "Copy the list in one sitecollection to another sitecollection"
    I have one list like "ABC" and with lookup column "Status" this column is looked to anthor list columns
    My task is i want to Copy the same list with lookup columns with Data(lookup columns Data) in one site and restored in another site.
    Error  is Lookup columns Data is not coming.
    How to Copied list with lookup columns data to restored in another list?
    Badri

    i think there is no such method to move the list with lookup column. 
    couple of things which cause the failure, Number Source list may be not available on the target site collection, Column IDs / List IDs different from Site collection a to B.
    I would try to use the backup of site collection and restore it, i am not sure whether it will work not.
    i think copy the data from the lookup clomn in the excel, then move the list to different site collection with blank data then copy the data from excel to new list.
    check this one for another idea:
    http://blog.johnsworkshop.net/moving-lists-with-lookup-columns-inside-your-site-collection/
    Please remember to mark your question as answered &Vote helpful,if this solves/helps your problem. ****************************************************************************************** Thanks -WS MCITP(SharePoint 2010, 2013) Blog: http://wscheema.com/blog

  • How to do inline assembly with cc

    Hi,
    i was looking for information on how to exactly formulate inline-assembly statements with the c compiler. However there were no usefull information available. Can you please point me to some locations, please.
    matthias

    There is basic inline assembler, which looks like:
    asm("assembler instruction here");
    You can try much more advanced gcc-style inline assembler with cc/CC, starting from Express 3.
    It is not fully implemented though, so you should restrict yourself to very basic constructs only.
    It works better on Sparc than on Intel. And you better compile with optimization...
    regards,
    __Fedor.

  • How to add a button with Javascript to Library

    Hi
    I am using Captivate 5.5 to create a template.
    In the files which will be created using this template, we will be adding a button which executes a Javascript. Now, my question is, since this button will be used on multiple slides in the file, can I add this button (with the Javascript) to the library? Currently, we create it manually everytime.
    We don't have a programmer in our team, so we can't create widget. Is there an alternative way?
    Thanks for your help.
    Sreekanth

    Thanks for that reply.
    I now have a blank slide with the button (including the javascript) on it which solves the problem of importing it manually.
    However, when we use this template to import PowerPoint presentations, when we publish the file, the first slide (the one on which I have this button) will be blank and has to be manually deleted.
    Is there a way to eliminate this manual work? I tried hiding and using some actions. But it was not of any use.

Maybe you are looking for

  • After running f.13 open items not cleared.

    Hi Experts, Though i cleared open items of Gl through f.13, but still it is showing as open item in FBL3n report. the GL is of Provision a/c. Edited by: poonam laddha on Dec 30, 2008 12:15 PM

  • When I try to select 'Manually manage music and videos' option?

    I know to manually manage songs/videos on itunes, i need to select the 'Manually manage music and videos' box under my iPhone 5S summary tab. However, when I check that box and click apply, this message pops up: http://prntscr.com/248mwn (this is a s

  • How to create a link

    i have to create a link in servlets ,this link should pop up a file where in client can modify this file & should be able to save it , i should also be able to receive this modified file. I have absolutely no idea of how to start can anyone on the li

  • Reversing Payroll Posting

    Dear Friends Assuming that an employee is resigning  on 25th May 2008, we did the full and final settlement for this employee.  Now the problem is he withdrawn the offer.  We have done the payroll posting last month for all the employee including thi

  • Value serch help issue in webdtnpro ABAP interactive form

    Hi Experts, Iam facing an issue with value search help filed in Adobe interactive form using webdynpro native . if i click on button search help is working but after selecting value in popup is not populating in respective field . Please guide me on