Stored procedure to export result to excel header not displayed

Hi,
I am using below stored procedure to export data to excel with header. but it is not displaying the header . i believe this is because the max length of query can be 8000. but  I have more than 250 columns so probably the length of query is breaking
the code.
can someone please help here.
Thanks in advance.
ALTER procedure [dbo].[proc_generate_excel_with_columns]
@table_name varchar(100),
@file_name varchar(100)
as
--Generate column names as a recordset
declare @columns varchar(8000), @sql varchar(8000), @data_file varchar(100)
select
@columns=coalesce(@columns+',','')+column_name+' as '+column_name
from
information_schema.columns
where
table_name=@table_name
select @columns=''''+replace(replace(@columns,' as ',''' as '),',',',''')
--Create a dummy file to have actual data
select @data_file=substring(@file_name,1,len(@file_name)-charindex('\',reverse(@file_name)))+'\data_file.csv'
--Generate column names in the passed EXCEL file
set @sql='bcp "select * from (select ' + @columns + ') as header" queryout E:\test.csv -c -t, -T -S ' + @@servername
exec master..xp_cmdshell @sql
--Generate data in the dummy file
set @sql='bcp "select * from CustomerTable where ReservationDate>''1/1/2013''" queryout E:\data_file.csv -c -t, -T -S' + @@servername
exec master..xp_cmdshell @sql
--Copy dummy file to passed EXCEL file
set @sql= 'exec master..xp_cmdshell ''type '+@data_file+' >> "'+@file_name+'"'''
exec(@sql)
----Delete dummy file
set @sql= 'exec master..xp_cmdshell ''del '+@data_file+''''
exec(@sql)
--EXEC proc_generate_excel_with_columns 'CustomerTable','E:\test.csv'

Can you try to print the @columns?
In the same procedure can you change size of @columns to varchar(max) and try executing the procedure?
ALTER procedure [dbo].[proc_generate_excel_with_columns]
@table_name varchar(100),
@file_name varchar(100)
as
--Generate column names as a recordset
declare @columns varchar(max), @sql varchar(max), @data_file varchar(100)
select
@columns=coalesce(@columns+',','')+column_name+' as '+column_name
from
information_schema.columns
where
table_name=@table_name
select @columns=''''+replace(replace(@columns,' as ',''' as '),',',',''')
print @Columns
--Create a dummy file to have actual data
select @data_file=substring(@file_name,1,len(@file_name)-charindex('\',reverse(@file_name)))+'\data_file.csv'
--Generate column names in the passed EXCEL file
set @sql='bcp "select * from (select ' + @columns + ') as header" queryout E:\test.csv -c -t, -T -S ' + @@servername
exec master..xp_cmdshell @sql
--Generate data in the dummy file
set @sql='bcp "select * from CustomerTable where ReservationDate>''1/1/2013''" queryout E:\data_file.csv -c -t, -T -S' + @@servername
exec master..xp_cmdshell @sql
--Copy dummy file to passed EXCEL file
set @sql= 'exec master..xp_cmdshell ''type '+@data_file+' >> "'+@file_name+'"'''
exec(@sql)
----Delete dummy file
set @sql= 'exec master..xp_cmdshell ''del '+@data_file+''''
exec(@sql)
--EXEC proc_generate_excel_with_columns 'CustomerTable','E:\test.csv'
--Prashanth

Similar Messages

  • Calling a Stored Procedure with a result set and returned parms

    I am calling a stored procedure from a Brio report. The stored procedure returns a result set, but also passes back some parameters. I am getting a message that states that the DBMS cannot find the SP with the same footprint. Besides the result set, the SP returns 3 out parameters: (Integer, char(60), char(40)). Is there something special I need to do in Brio to format the out parameters to be passed back from the SP.
    Thanks,
    Roland

    Did you try just declaring the vars?
    untested
    declare
      myCur SYS_REFCURSOR;
      myRaw RAW(4);
      BEGIN
        test (0, 0, myRaw, sysdate, myCur);
      END;

  • How to create Store Procedure for export result select in .txt or .csv

    Hello,
    I'm using MSSQL Server.
    How to export results query  in .txt or .csv?
    But
    I can not use bcp or SQLCMD.

    1) linked server
    insert into txtsrv...table1#txt(CustomerNumber,CustomerName,EntryDate)
    select orderid, shipname, orderdate
    from Northwind..orders
    Set up the linked server
    Connecting a directory of text files as a linked server is easy.  Here’s how:
    In Windows, create a new directory for the linked server.  
    For this article, that directory will be E:\txtsvr. 
    Add that directory as a linked server with sp_addlinkedserver:
    EXEC sp_addlinkedserver txtsrv, 'Jet 4.0',
      'Microsoft.Jet.OLEDB.4.0', 'e:\txtsrv', NULL, 'Text' 
    That’s all that’s required to add the linked server txtsrv
     as a connection to the text files in E:\txtsvr, but there are
     no tables in txtsvr yet.  Also missing is a required file, schema.ini, 
    which must contain a description of each table’s format.  
    You can  learn more about schema.ini from the Microsoft MSDN Library,
     but for now, just use Notepad or your favorite text editor 
    to create the file e:\txtsrv\schema.ini as shown in Listing 1. 
     In addition, create an empty text file in e:\txtsrv named table1.txt.
    The file e:\txtsrv\table1.txt is now an empty table in the linked server txtsrv.  
    We can see that if we list information about all the tables in txtserv with 
    the system stored procedure sp_tables_ex:
    EXEC sp_addlinkedsrvlogin txtsrv, FALSE, Admin, NULL
    EXEC sp_tables_ex txtsrv
    Text files are tables
    We can’t issue a CREATE TABLE statement against this linked server, 
    but we have created a table easily enough.  We can, however, 
    run INSERT and SELECT queries, if we use the four-part naming 
    convention <server>…<table> (that’s three dots):
    Best Regards,Uri Dimant SQL Server MVP,
    http://sqlblog.com/blogs/uri_dimant/
    MS SQL optimization: MS SQL Development and Optimization
    MS SQL Consulting:
    Large scale of database and data cleansing
    Remote DBA Services:
    Improves MS SQL Database Performance
    SQL Server Integration Services:
    Business Intelligence

  • How to use stored procedure which returns result set in OBIEE

    Hi,
    I hav one stored procedure (one parameter) which returns a result set. Can we use this stored procedure in OBIEE? If so, how we hav to use.
    I know we hav the Evaluate function but not sure whether I can use for my SP which returns result set. Is there any other way where I can use my SP?
    Pls help me in solving this.
    Thanks

    Hi Radha,
    If you want to cache the results in the Oracle BI Server, you should check that option. When you run a query the Oracle BI Server will get its results from the cache, based on the persistence time you define. If the cache is expired, the Oracle BI Server will go to the database to get the results.
    If you want to use caching, you should enable caching in the nqsconfig.ini file.
    Cheers,
    Daan Bakboord

  • Help me in calling stored procedure and getting results

    hi
    i have a SP like this
    CREATE OR REPLACE PACKAGE P1 AS
    TYPE g_con_ref_cursor is REF CURSOR ;
    TYPE g_con_error IS RECORD
      error_code NUMBER,
      error_desc varchar2(2000)
    PROCEDURE PROC_CURSOR
    (i_str_userid  IN VARCHAR2,
      o_cur_ref_cur OUT g_con_ref_cursor,
      o_rec_error   OUT g_con_error,
      o_num_status  OUT NUMBER);
    END;
    and i now i am trying to call this SP using my java program
    i am able to register the out put params for 2nd and 4 th variable
    my doubt is how i can register the output param for g_con_errorand how i can get result from this ????
    my java program is like this
    Connection connection = DatabaseHelper.prepareConnection();
    CallableStatement proc = connection.prepareCall("{ call P1.PROC_CURSOR(?, ?, ?, ?) }");
    proc.setString(1,"jn26557");
    proc.registerOutParameter(2,oracle.jdbc.driver.OracleTypes.CURSOR);
    proc.registerOutParameter(3,Types.STRUCT,); //HOW TO SET  THIS ?????
    proc.registerOutParameter(4,oracle.jdbc.driver.OracleTypes.NUMERIC);
    proc.execute();
    plz help me in this
    i have no idea how to do it
    any help would be appreciated
    Thanks in advance
    Jaya Prakash Nalajala

    You have the requirements to build the stored procedure, what have you got so far?
    Post your attempt and any errors or issues that you might be experiencing. Writing the whole procedure for you (without the table structure even) is going to be difficult.

  • Like in stored procedure returns incorrect result

    Hello all,
    I have a stored procedure like below
    Alter PROCEDURE ContactsListBySearch
    @AuthorID int,
    @currentPage INT,
    @pageSize INT,
    @searchStr nvarchar
    AS
    BEGIN
    set nocount on;
    WITH tempLog AS (
    SELECT distinct ROW_NUMBER()OVER (ORDER BY email DESC) AS Row,
    email,username from AddContact where userid = @AuthorID and email like '%'+@searchStr+'%' and username like '%'+@searchStr+'%' )
    SELECT email,username
    FROM tempLog
    WHERE Row between ((@currentPage - 1) * @pageSize + 1) and (@currentPage*@pageSize)
    END
    for a search string david it gives me unrelated rows.
    But for the same query string david if i run the query
    select email,username from addcontact where userid=2 and email like '%david%' and username like '%david%'
    It gives me exact result.
    How to pass an paramter as a string in the stored procedure?? please help me.
    regards,
    Guru
    Edited by: user4554966 on Jan 18, 2010 6:45 PM

    Did not get any help from them ;)
    Regards,
    Guru

  • Calling an Oracle stored procedure and retrieving result from OUT parameter

    Hello,
    I have a stored procedure that returns a string in an OUT parameter after receiving 6 IN parameters. I have tested the procedure in PL/SQL and it's producing the right output there. The problem is when I call the stored procedure from my Java method. I then get an error message telling me that I have the wrong number or types of arguments in my procedure call. I have checked that the method receives and sends the correct data in the correct order and I'm not sure what else the error message can relate to...?
    The exception is called on my second try statement but I haven't been able to find out what I have done wrong there. Does anyone have any suggestions? Thanks.
    the error message
    java.sql.SQLException: ORA-06550: line 1, column 13: PLS-00306: wrong number or types of arguments in call to 'P_SET_GIVEN_ANSWER' ORA-06550: line 1, column 7: PL/SQL: Statement ignored
    the procedure
    CREATE OR REPLACE PROCEDURE p_set_given_answer(
    strfeedback OUT VARCHAR2,
    intpi_id IN INTEGER,
    intquestion_id IN INTEGER,
    intgivenanswer IN INTEGER,
    strgivenprefix IN VARCHAR2,
    strgivenunit IN VARCHAR2,
    strgu_id IN VARCHAR2) AS
    -- some declarations
    BEGIN
    -- some processing and then returns the string below indicating the outcome
    strfeedback = 'result';
    END
    the java method (the class is called dbUtil and the database connection is created in the method called getDbConnection() )
    public void setGivenAnswer(int intPi_id, int intQuestion_id, int intGivenAnswer, String strGu_id, String strGivenPrefix, String strGivenUnit) {
    java.sql.Connection con = null;
    String query = "{call ? := p_set_given_answer(?,?,?,?,?,?)}";
    try {
    con = dbUtil.getDbConnection();
    } catch(Exception e) {
    dbConnectionExceptionMessage = "error 1:"+e.toString();
    try{
    CallableStatement stmt = con.prepareCall(query);
    // register the type of the out param - an Oracle specific type
    stmt.registerOutParameter(1, OracleTypes.VARCHAR);
    // set the in params
    stmt.setInt(2, intPi_id);
    stmt.setInt(3, intQuestion_id);
    stmt.setInt(4, intGivenAnswer);
    stmt.setString(5, strGivenPrefix);
    stmt.setString(6, strGivenUnit);
    stmt.setString(7, strGu_id);
    // execute the stored procedure
    stmt.execute();
    // retrieve the results
    strFeedback = stmt.getString(1);
    } catch (java.sql.SQLException e) {
    dbConnectionExceptionMessage = "error 2:"+e.toString();
    try {
    con.close();
    } catch (java.sql.SQLException e) {
    dbConnectionExceptionMessage = "error 3:"+e.toString();
    ----------------------------------------

    Looks like you are declaring a procedure, but you are calling it like a function. A procedure has no return value, it has only parameters: "{call p_set_given_answer(?,?,?,?,?,?,?)}"

  • Stored Procedure With Multiple Result Sets As Report Source : Crosspost

    Hello Everyone,
    I have an issue where i have created a stored procedure that returns multiple result sets
    /* Input param = @SalesOrderID */
    SELECT * FROM Orders TB1
      INNER JOIN OrderDetails TB2 ON  TB1.ID = TB2.ID
    WHERE TB1.OrderID = @SalesOrderID
    SELECT * FROM Addresses
      WHERE Addresses.OrderID = @SalesOrderID AND Addresses.AddressType = 'Shipping'
    SELECT * FROM Addresses
      WHERE Addresses.OrderID = @SalesOrderID AND Addresses.AddressType = 'Billing'
    This is just a quick sample, the actual procedure is a lot more complex but this illustrates the theory.
    When I set the report source in Crystal X to the stored procedure it is only allowing me to add rows from the first result set.
    Is there any way to get around this issue?
    The reason that I would prefer to use a stored procedure to get all the data is simply performance. Without using one big stored procedure I would have to run at least 6 sub reports which is not acceptable because the number of sub reports could grow exponentially depending on the number of items for a particular sales order.
    Any ideas or input would be greatly appreciated.
    TIA
        - Adam
    P.S
    Sorry for the cross post, I originally posted this question [here|/community [original link is broken];
    but was informed that it might be the wrong forum
    Edited by: Adam Harris on Jul 30, 2008 9:44 PM

    Adam, apologies for the redirect, but it is better to have .NET posts in one place. That way anyone can search the forum for answers. (and I do not have the rights to move posts).
    Anyhow, as long as the report is created, you should be able to pass the datasets as:
    crReportDocument.Database.Tables(0).SetDataSource(dataSet.Tables("NAME_OF_TABLE"))
    Of course alternatively, (not sure if this is possible in your environment) you could create a multi-table ADO .NET dataset and pass that to the report.
    Ludek

  • Saved PDF from Stored Procedure missing application item in report header

    I am able to create and save the pdf from a stored procedure however the application item that contains the date is blank in the saved pdf. Report title displays correctly when running via APEX. I have tried to set this value with, apex_util.set_session_state('F111_DATE',sysdate); and also as a cookie owa_cookie.send('F11_DATE',to_char(sysdate,'Month DD, YYYY'));
    and neither of these statements work. Example of code below...
    vRequest := Utl_Http.begin_request(vReportUrl,'POST');
    Utl_Http.set_header(vRequest, 'User-Agent', 'Mozilla/4.0');
    owa_cookie.send('F11_DATE',to_char(sysdate,'Month DD, YYYY'));
    apex_util.set_session_state('F111_DATE',sysdate);
    vResponse := Utl_Http.get_response(vRequest);
    Apex version 3.2/ 11g

    There are also some great resources on OTN:
    How-To's: http://www.oracle.com/technology/products/database/application_express/howtos/howtos.html
    Tips and Tricks:
    http://htmldb.oracle.com/pls/otn/f?p=18326:50:3390956087894876
    And check out Scott Spendolini & Carls Blog:
    http://spendolini.blogspot.com/
    http://blogs.oracle.com/carlback/
    These are all great resources for picking up some really cool stuff.
    Regards
    Duncan

  • Dynamically calling stored procedure and getting result set c++

    Hello,
    I am trying to write some c++ code that will dynamically bind values to a stored procedure and excute the procedure and get back a resultset. The problem I am running into is how to get back the resultset. Any help or example would be highly appreciated.

    int main(int argc, char* argv[])
    OCIError* pOciError;
    char* pConnectChar = "dbname";
    char* pUsernameChar = "scott";
    char* pPasswordChar = "tiger";
    int answer;
    OCIStmt* pOciStatement;
    char* sqlCharArray = "BEGIN :success := sp_ListEmp; END;";
    int id;
    char ename[40];
    OCIEnv* g_pOciEnvironment = NULL;
    OCIServer* g_pOciServer = NULL;
    OCISession* g_pOciSession = NULL;
    OCISvcCtx* g_pOciServiceContext = NULL;
    sb2* pIndicator=0;
    sb2* pIndicator2=0;
    sb2* pIndicator3=0;
    OCIDefine* pOciDefine;
    OCIDefine* pOciDefine2;
    OCIBind* pBind;
    OCIStmt* cursor;
    answer = OCIInitialize(OCI_THREADED, NULL, NULL, NULL, NULL);
    answer = OCIEnvInit(&g_pOciEnvironment, OCI_DEFAULT, 0, NULL);
    answer = OCIHandleAlloc(g_pOciEnvironment, (void **)&pOciError, OCI_HTYPE_ERROR, 0, NULL);
    answer = OCIHandleAlloc(g_pOciEnvironment, (void **)&g_pOciSession, OCI_HTYPE_SESSION, 0, NULL);
    answer = OCIHandleAlloc(g_pOciEnvironment, (void **)&g_pOciServer, OCI_HTYPE_SERVER, 0, NULL);
    answer = OCIHandleAlloc(g_pOciEnvironment, (void **)&g_pOciServiceContext, OCI_HTYPE_SVCCTX, 0, NULL);
    answer = OCIServerAttach(g_pOciServer, pOciError, (unsigned char *)pConnectChar, strlen(pConnectChar),
    OCI_DEFAULT);
    answer = OCIAttrSet(g_pOciSession, OCI_HTYPE_SESSION, (unsigned char *)pUsernameChar, strlen(pUsernameChar),
    OCI_ATTR_USERNAME, pOciError);
    answer = OCIAttrSet(g_pOciSession, OCI_HTYPE_SESSION, (unsigned char *)pPasswordChar, strlen(pPasswordChar),
    OCI_ATTR_PASSWORD, pOciError);
    answer = OCIAttrSet(g_pOciServiceContext, OCI_HTYPE_SVCCTX, g_pOciServer, 0, OCI_ATTR_SERVER, pOciError);
    answer = OCIAttrSet(g_pOciServiceContext, OCI_HTYPE_SVCCTX, g_pOciSession, 0, OCI_ATTR_SESSION, pOciError);
    answer = OCISessionBegin(g_pOciServiceContext, pOciError, g_pOciSession, OCI_CRED_RDBMS, OCI_DEFAULT);
    answer = OCIHandleAlloc(g_pOciEnvironment, (void **)(&pOciStatement), OCI_HTYPE_STMT, 0, NULL);
    answer = OCIStmtPrepare(pOciStatement, pOciError, (unsigned char *)sqlCharArray, strlen(sqlCharArray),
    OCI_NTV_SYNTAX, OCI_DEFAULT);
    answer = OCIHandleAlloc(g_pOciEnvironment, (void **)(&cursor), OCI_HTYPE_STMT, 0, NULL);
    answer = OCIBindByPos(pOciStatement,&pBind, pOciError, 1, &cursor, 0,SQLT_RSET,
    pIndicator2, 0,NULL, 0,0,OCI_DEFAULT);
    answer = OCIStmtExecute(g_pOciServiceContext, pOciStatement, pOciError, 1, 0, NULL, NULL,
    OCI_COMMIT_ON_SUCCESS);
    answer = OCIDefineByPos(cursor,&pOciDefine, pOciError,2,&id,sizeof(int),
    SQLT_INT,pIndicator, 0, 0,OCI_DEFAULT);
    answer = OCIDefineByPos(cursor,&pOciDefine2, pOciError,1,ename,40,
    SQLT_STR,pIndicator3, 0, 0,OCI_DEFAULT);
    if (answer == 0)
    while ((answer = OCIStmtFetch(cursor,pOciError, 1,OCI_FETCH_NEXT,OCI_DEFAULT)) == 0)
    printf("fetched id %d and name %s\n",id,ename);
    answer = OCIHandleFree(pOciError, OCI_HTYPE_ERROR);
    return 0;

  • Why are my JPEG exports from Lightroom 4 are not displaying on other computers?

    When I export JPEGs from Lightroom, they display fine on my computer but when I send them to the client, they are not displaying at all. There is a message saying that the software on the clients computer may not be up to date so I tried updating their software but to no avail.

    I know, it's strange. I've never encountered it before. They are definitely JPEGs, although I don't know if the difference between JPGs and JPEGs is anything to consider.
    On my computer, 2008 MacBook Pro, OS 10.8.3, they display through Preview. Also, when I upload them to Dropbox, the thumbnails display correctly. I have transferred them to a USB key as my client was not tech savvy enough to grasp Dropbox. When I brought the USB Key to the client and transferred to her MacBook Air, neither the thumbnails nor the photos themselves displayed. I also tried transferring to her PC and the same result.
    I was trying to contact Adobe support to see if this was a problem other people had experienced.

  • BI Publisher - Header not displayed

    Hi All,
    I have created a rtf template using MSWord and have used the Word Header to insert header information. I loaded xml data to the template and when I preview it in pdf format, the Header information is not displayed on the pdf form. I tried to preview in Excel, HTML formats also but none of them displayed the header.
    It used to work earlier for me. I re-installed BI Publisher plug-in thinking that I might have disturbed any settings on the BI Publisher Add-in...but it still does not work.
    Any suggestions would be sincerely appreciated.
    Thanks,
    Pramod

    Thanks for the checklist.
    -Does it show text or a picture if you put that in the header? - No text or picture displayed on pdf
    - What is your page layout? Potrait, with suitable margins for Top and bottom of page
    - If you are just in Word and print the page to pdf, do you see your header? - No. I receive an error "There was an error found when printing the document 'Microsoft Word - Doc1.rtf to My Documents \*.pdf"
    Does this mean the Adobe Acrobat is having any issues?

  • EXCEL output not displaying properly

    We are using XML publisher 5.0 with Oracle Financial Applications.
    We have defined Viewer Options for Excel as
    File Format=Excel, Mime Type=application/vnd.ms-excel.
    The problem is when we use web based View requests, the excel comes up with XML code in it. We are not sure why excel is not interpreting the XML output.
    Please help.
    Thanks
    Kishore

    I can not see any option for excel viewing under sys admin -> profile -> system menu. The profiles available there are:
    Profile     Site     
    Viewer: Application for HTML                                   
    Viewer: Application for PCL                                   
    Viewer: Application for PDF                                   
    Viewer: Application for PostScript                                   
    Viewer: Application for Text     Microsoft Word                              
    Viewer: Application for XML     Browser                              
    Viewer: Default Font Size     10                              
    Viewer: HTML     C:\MSOffice\Winword\Winword.exe $$FILE$$                              
    Viewer: PDF     C:\Acrobat3\Reader\AcroRd32.exe $$FILE$$                              
    Viewer: PostScript     C:\MSOffice\Winword\Winword.exe $$FILE$$                              
    Viewer: Text                                   
    Please let me know where to set the xl profile value.
    Thanks
    Varun

  • Page Header Not Displaying at Top of Page

    Report Builder 3
    We have a number of reports that include navigation links in the page header. The links use the Bookmarks Action to move the user to a different page. The pages are separated using Page Breaks. Below is an example:
    > Top row is the Page Header.
    > Second section is the Resource Listing & Alerts page.
    > After the first page a rectangle is placed which has Page Break set to Start.
    > After the rectangle comes the start of the "Data Extract" page. The title is in a rectangle with a Bookmark called Page2.
    > Click the link to be forwarded to the Data Extract.
    > Page displays, but the Page Header is not visible because the screen is scrolled down slightly.
    I have not been able to fix this or find a workaround that forces the Page Header to always display at the top. It has been suggested that putting the page break before the bookmark would force this to work, but that is not working.
    Any ideas?     Thank you! Naamkeek

    Hi  Naamkeek,
    Based on my understanding, you add a bookmark link for “Data Extract” in page header, however, when clicking this fields, other page displays without visible page header.
    In Reporting Service, when setting page header in a report, the page header will display in each report page. In your scenario, since you set BreakLocation as Start in PageBreak property, the rectangle could make the page header upper and screen scroll down
    lightly. So please change this property to End. As we tested in our environment, we set BreakLocation as End in PageBreak property for the blank rectangle. Then adding a bookmark link in page header, when we click “Data Extract”, the page header will appear
    on a new page. Please refer to screenshots below:
    Reference:
    Page Headers and Footers (Report Builder and SSRS)
    Best regards,
    Qiuyun Yu

  • Group Header not displaying on conditional suppression

    I have a report that is used to audit controlled medications.  It is grouped by patient and then by medication order ID.  I only want to display the data when the patient has had their medication ordered more than once.  I have a test patient who is not displaying on my report and I have figured out why, but no clue as how to fix it.  Does anyone have any ideas?  The reason why the test patient in question is not displaying is because they have three medication orders of different medications.  Only one of these was ordered more than once.  I believe my suppression formula is only catching the first medication order and since the line is never greater than one on that, his header won't display....  How can I evaluate all of his different medication orders?
    IF distinctcount({ORDER_MED.ORDER_MED_ID}, {PATIENT.PAT_MRN_ID}) >1 then
       if  count({ORDER_AUDIT_TRL.line}, {ORDER_MED.ORDER_MED_ID})>1 then
          false
      else
           true
    else if
    count({ORDER_AUDIT_TRL.line}, {ORDER_MED.ORDER_MED_ID})<=1 then
            true

    I think I just figured this out....
    I added this to the group selection criteria...
    count({ORDER_AUDIT_TRL.line}, {ORDER_MED.ORDER_MED_ID})>1

Maybe you are looking for