How to create a function with dynamic sql or any better way to achieve this?

        Hello,
        I have created below SQL query which works fine however when scalar function created ,it
        throws an error "Only functions and extended stored procedures can be executed from within a
        function.". In below code First cursor reads all client database names and second cursor
        reads client locations.
                  DECLARE @clientLocation nvarchar(100),@locationClientPath nvarchar(Max);
                  DECLARE @ItemID int;
                  SET @locationClientPath = char(0);
                  SET @ItemID = 67480;
   --building dynamic sql to replace database name at runtime
         DECLARE @strSQL nvarchar(Max);
         DECLARE @DatabaseName nvarchar(100);
         DECLARE @localClientPath nvarchar(MAX) ;
                  Declare databaselist_cursor Cursor for select [DBName] from [DataBase].[dbo].
                  [tblOrganization] 
                  OPEN databaselist_cursor
                  FETCH NEXT FROM databaselist_cursor INTO @DatabaseName
                  WHILE @@FETCH_STATUS = 0
                  BEGIN       
   PRINT 'Processing DATABASE: ' + @DatabaseName;
    SET @strSQL = 'DECLARE organizationlist_cursor CURSOR
    FOR SELECT '+ @DatabaseName +'.[dbo].[usGetLocationPathByRID]
                               ([LocationRID]) 
    FROM '+ @DatabaseName +'.[dbo].[tblItemLocationDetailOrg] where
                               ItemId = '+ cast(@ItemID as nvarchar(20))  ;
     EXEC sp_executesql @strSQL;
    -- Open the cursor
    OPEN organizationlist_cursor
    SET @localClientPath = '';
    -- go through each Location path and return the 
     FETCH NEXT FROM organizationlist_cursor into @clientLocation
     WHILE @@FETCH_STATUS = 0
      BEGIN
       SELECT @localClientPath =  @clientLocation; 
       SELECT @locationClientPath =
@locationClientPath + @clientLocation + ','
       FETCH NEXT FROM organizationlist_cursor INTO
@clientLocation
      END
       PRINT 'current databse client location'+  @localClientPath;
     -- Close the Cursor
     CLOSE organizationlist_cursor;
     DEALLOCATE organizationlist_cursor;
     FETCH NEXT FROM databaselist_cursor INTO @DatabaseName
                END
                CLOSE databaselist_cursor;
                DEALLOCATE databaselist_cursor;
                -- Trim the last comma from the string
               SELECT @locationClientPath = SUBSTRING(@locationClientPath,1,LEN(@locationClientPath)-  1);
                 PRINT @locationClientPath;
        I would like to create above query in function so that return value would be used in 
        another query select statement and I am using SQL 2005.
        I would like to know if there is a way to make this work as a function or any better way
        to  achieve this?
        Thanks,

This very simple: We cannot use dynamic SQL from used-defined functions written in T-SQL. This is because you are not permitted do anything in a UDF that could change the database state (as the UDF may be invoked as part of a query). Since you can
do anything from dynamic SQL, including updates, it is obvious why dynamic SQL is not permitted as per the microsoft..
In SQL 2005 and later, we could implement your function as a CLR function. Recall that all data access from the CLR is dynamic SQL. (here you are safe-guarded, so that if you perform an update operation from your function, you will get caught.) A word of warning
though: data access from scalar UDFs can often give performance problems and its not recommended too..
Raju Rasagounder Sr MSSQL DBA
      Hi Raju,
       Can you help me writing CLR for my above function? I am newbie to SQL CLR programming.
       Thanks in advance!
       Satya
          

Similar Messages

  • How to create a function with ref_cursor as parameter in OWB 10.1

    Hi,
    Can any one help me how to create a function with ref_cursor as parameter in OWB 10.1.?
    Its urgent. Please help me.
    Thanks,
    Siv

    Hi David,
    Thanks for your reply.
    Before going for this function, I need to create a package in transformation node in owb module.
    My package is as follows,
    Create or replace package 123
    type xxx is RECORD ( parameters);
    type yyy is RECORD (parameters);
    type aaa is table of yyy;
    type bbb is REF CURSOR return xxx;
    type ccc is record (parameters);
    type ddd is ref cursor return eee;
    END;
    How can I create the above kind of package manually in OWB 10.1 (Should not to import the package)
    Please help me its urgent.
    Thanks,
    Siv

  • How to call a function with pl/sql

    How does one call a function with pl/sql that uses a function?

    Hi,
    How does one call a function with pl/sql that uses a
    function?I'm not sure what you mean.
    In PL/SQL function can be used just about anywhere where an expression (with the same data type that the function returns). Arpit gave a very common example.
    Here's another example, where all the functions take a single NUMBER argument and return a NUMBER, so they can all be used in places where NUMBERs are used:
    IF  fun_a (fun_b (0)) < fun_c (1)
    THEN
        UPDATE  table_x
        SET     column_y = fun_d (2)
        WHERE   column_z = fun_e (ROUND ((fun_f (3), fun_g (4)));You call a function simply by using its name, followed by its argument list, if any.
    If the function is in a package, you must call it with the package name, like "pk_foo.bar (1, 2, 3)", unless the call comes from within the same package.
    If the function is owned by someone else, you must give the owner name, like "scott.bar (SYSDATE)" or "scott.pk_foo.bar (1, 2, 3)". You can create synonyms to avoid having to name the owner.

  • How to find out whether my Iphone 3Gs is officlially unlocked ( factory unlocked ) or "made" unlocked ? Can I upgrade its OS to OS 5 even if my phone is "made" unlocked ? how to up gared its OS ? are there any better ways to do it ?

    How to find out whether my Iphone 3Gs (OS version 3.1.3) is officlially unlocked ( factory unlocked ) or "made" unlocked ? Can I upgrade its current OS 3.1.3 to OS 5 even if my phone is not officlially unlocked ? how to up grade its OS ? what are there any better ways to do it ?
    Thanks,
    PRANAJ

    Depends wher you obtained the iPhone from and it's original supplier
    If the iPhone is an authorised unlock ( approved by the carrier) or was
    purchased from Apple as an unlocked iPhone  updating the iOS
    will have no effect on the iPhone and it's lock status
    HOWEVER if the software has been tampered with to remove the lock,
    updating the iOs will lock the iPhone back to the original carrier who holds the lock
    To find out the status of your iPhone  you could call Apple support
    and they may tell you if the iPhone is locked or not and if it is which carrier

  • How to create a report with dynamic columns

    Hi all,
    I am using Apex 4.0 with Oracle 10g
    I am creating a report and I need to display columns dynamically based on the item values.
    example:
    I have a table employee with columns name, designation, sal
    In the report page i have a select list with designations and when I select a designation from the select list,
    I need to display the names of the employees horizontally,
    like each name as a new column in the report with that particular designation. and same has to continue when I select different designations.
    Can some one help me how we can do that.
    I appreciate your answer
    Thanks,
    Rik

    Essentially you want to write a pl/sql function which returns a varchar2 string. The contents of the string must be a valid sql statement.
    Once you have done this, you need to add a report region as type sql report and you will have the option of writing it as a query or as a function returning query. Choose function returning query and enter in the function call.
    Note your function must be valid, and must be executable by your apex parsing schema.
    example:
    create or replace
    function test_report(   p1_tablename       in varchar2)
    return varchar2
    is
    v_query varchar2(4000);
    begin
    v_query  :=
    'SELECT * from '||p_tablename;
    return v_query;
    end test_report;Edited by: Keith Jamieson on Aug 15, 2011 4:50 PM

  • How to call javascript function with dynamic data in display tag

    Hi,
    Iam new to pagination concept. Iam using display tag to display rows in jsp by strtus.
    I have a problem when calling the javascript function using ahref in attribute in display tag.
    <bean:define name="form1" property="EditDetails.List" id="ListDisplay"/>
    <display:table name="pageScope.ListDisplay" cellpadding="0" cellspacing="1" pagesize="10" partialList="false" size="listSize" requestURI="">
    <display:column property="poNo" href='javascript:searchEditDetails("./submitOrder.do? actionID=getMISLoadEdit&poNumberSel=<%=((com.po.bean.EditDetails)poListDisplay).getNo()%>&statusIdSelected=<%=((com.po.bean.EditDetails)ListDisplay).getStatusId()%>")'
    title="Number"/>                         
    <display:column property="strDate"title="Date" />
    <display:column property="orderValue"title="Order Value(INR)"/>
    <display:column property="stringRequestedDeliveryDate"title="Suggested Delivery Date"/>
    <display:column property="statusDescription" title="Status" />
    </display:table>
    The above code display the data in row format is working fine when I click the No It thow javascript error and its not redirecting to the other page.
    When I try this with ordinary struts its working fine the code is:
    <logic:iterate id="polist" name="Form1" property="EditDetails.List" indexId="i" type="com.bean.EditDetails">
    <tr>
    <td ><a href="javascript:searchEditDetails("./submitOrder.do?actionID=getMISLoadEdit&NumberSel=<%=((com.bean.EditDetails)polist).getNo()%>&statusIdSelected=<%=((com.bean.EditDetails)polist).getStatusId()%>")"><html:hidden name="polist" property="No" write="true" /></a>     </td>
    <td><html:hidden name="polist" property="strDate" write="true" /></td>
    <td><html:hidden name="polist" property="orderValue" write="true" /></td>
    <td><html:hidden name="polist" property="stringRequestedDeliveryDate" write="true" />     </td>
    <td><html:hidden name="polist" property="statusDescription" write="true" /></td>
    </tr>
    </logic:iterate>
    Please help me how to call javascript with dynamic data.
    Thanks in advance

    The ADF Mobile Container Utilities API may be used from JavaScript or Java.
    Application Container APIs - 11g Release 2 (11.1.2.4.0)

  • How to create number ranges with "OK60" transaction or any other.

    Hello,
    I need to create a new number range to asigne to a document type , using transaction OK60 ( the error says this transaction).
    but I only can display with this transaction, and I would like to update.
    Is there any other transaction to do this , or is there any way to do this with this transaction OK60?
    Thank you very much.
    Kind regards
    Olga

    Hi,
    OK60 indeed is used for creating number ranges for FI/CO earmarked funds transactions. You should press on 'Pencil' button and create an interval. If for some reasons, you cannot do this via this transaction, try using SNRO transaction, with IRW_BELEG parameter. If this also fails, then apply to BASIS team to check your authorizations.
    Regards,
    Eli

  • How to create fillable PDF with dynamic content dropdowns?

    I'm creating a March Madness bracket for people that don't really understand how they work.  What I'd like to do is have dropdowns for each of bracket lines (they would list the teams playing against each other for that game and they would select who they think would win).  I would then like the dropdown for the next game to auto-populate with only the two options for the next round. 
    For example, team A and team B play against each other and teams C and D play against each other.  There are two separate dropdowns, one with A and B as choices and the other with C and D as choices.  The user thinks A and C will win their games, so the next dropdown would only have the options of selecting A and C.  To illustrate:
    AA and B are listed in the dropdown, and the user selects A to win.
    BA or C are listed in the dropdown because the user has selected A and C to win their previous games.
    CC and D are listed in the dropdown, and the user selects C to win.
    D
    I can make the first round dropdowns just fine, but I'm not sure how to conditionally/dynamically populate the second round dropdowns based off of user selections.

    I don't understand your request but my english is not the best.
    But here you can see a script. You can copy this in the first dropdown in the exit-event.
    In this example you will give the first dropdwon the entries
    "123"
    "345"
    "678"
    The first case describes what happens when the user clicks "123" the second drowdown will get the entries "456" and "789".
    When the user clicks "456" the second drowdown will get the entries "123" and "789".
    I think you can adapt this script as you need.
    Hope I could help a little bit,
    Mandy
    switch (xfa.event.newText)
        case "123":
            DropdownListe2.clearItems();
            DropdownListe2.addItem("Please select a value");
            DropdownListe2.addItem("456");
            DropdownListe2.addItem("789");
            DropdownListe2.selectedIndex = 0;
            break;
        case "456":
            DropdownListe2.clearItems();
            DropdownListe2.addItem("Please select a value");
            DropdownListe2.addItem("123");
            DropdownListe2.addItem("789");
            DropdownListe2.selectedIndex = 0;
            break;
        case "789":
            DropdownListe2.clearItems();
            DropdownListe2.addItem("Please select a value");
            DropdownListe2.addItem("123");
            DropdownListe2.addItem("456");
            DropdownListe2.selectedIndex = 0;
            break;
        default:
            break;

  • How to create a report with dynamic no of columns

    Hi All,
    we have a report with 6 columns.
    and its been access by 10-20 people.
    the user dont want to have a fix report with 6 columns rather they want to have a flexibility to select the columns from the report they want to see.
    i.e. user one one time wasnt to see only one columns
    another time he want to see only column 2 and 4 of the report.
    its like there can be a multiple select option from where he can select the columns in the existing report and then see the same report with only that much column.
    Please tell me how to implement it.

    Abhip i thin you didnt get the problem.
    there is s exeiting report with 6 column
    Currently when i logging to OBIEE and see that report
    i will be getting report with 6 column
    but now i want a flexibility of selecting only 2 or 3 or 1 or 4 or 5 as i wish columns from this report and see the result only for that
    so is there by any chance i can have a check box for each column which i can check in dashborad to select that column
    and show the result were as by default it will show the report with 6 column.
    Thanks

  • Create SCOM Group with dynamic members about 10minutes !

    in our SCOM 2012 SP1 (CU3) environment with about 800 Windows Agents.
    OperationsDB on a Windows Cluster (2 physical server with 2 processors (six cores). Datawarehouse on separate cluster.
    When i create a group with dynamic members, it took about 10min. During this period all the consoles are busy and freezing. 
    Is that normal ?
    Regards
    Lehugo

    on the management server i got follow eventlog error durung this time: 
    OpsMgr Management Configuration Service failed to execute 'ConfigStoreStatsUpdate' engine work item due to the following exception
    Microsoft.EnterpriseManagement.ManagementConfiguration.DataAccessLayer.DataAccessException: Data access operation failed
       at Microsoft.EnterpriseManagement.ManagementConfiguration.DataAccessLayer.DataAccessOperation.ExecuteSynchronously(Int32 timeoutSeconds, WaitHandle stopWaitHandle)
       at Microsoft.EnterpriseManagement.ManagementConfiguration.SqlConfigurationStore.ConfigurationStore.ExecuteOperationSynchronously(IDataAccessConnectedOperation operation, String operationName)
       at Microsoft.EnterpriseManagement.ManagementConfiguration.SqlConfigurationStore.ConfigurationStore.WorkItemCompleted(IConfigServiceEngineWorkItemHandle workItemHandle, IConfigServiceEngineWorkItemResult workItemResult)
       at Microsoft.EnterpriseManagement.ManagementConfiguration.Interop.SharedWorkItem.ExecuteWorkItem()
       at Microsoft.EnterpriseManagement.ManagementConfiguration.Interop.ConfigServiceEngineWorkItem.Execute()
    System.Data.SqlClient.SqlException (0x80131904): Sql execution failed. Error 50000, Level 16, State 1, Procedure WorkItemMarkCompleted, Line 61, Message: Failed to report work item completion. Work item with id 1888748 is not assigned to service instance 'XXXXXX\Default'
       at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)
       at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning()
       at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
       at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
       at System.Data.SqlClient.SqlCommand.CompleteAsyncExecuteReader()
       at System.Data.SqlClient.SqlCommand.EndExecuteNonQuery(IAsyncResult asyncResult)
       at Microsoft.EnterpriseManagement.ManagementConfiguration.DataAccessLayer.NonQuerySqlCommandOperation.SqlCommandCompleted(IAsyncResult asyncResult)

  • Creating Report using EPM Functions with Dynamic Filters

    Hi All,
    I am new to BPC, In BPC 7.5 i seen like we can generate EPM report using EVDRE function very quickly and easy too. Is the same feature is existing in BPC 10.0 ? if no how can we create EPM reports using EPM Functions with Dynamic Filters on the Members of the dimension like in BPC 7.5.
    And i searched in SDN, there is no suitable blogs or documents which are related to generation of Reports using EPM Functions. All are described just in simple syntax way. It is not going to be understand for the beginners.
    Would you please specify in detail step by step.
    Thanks in Advance.
    Siva Nagaraju

    Siva,
    These functions are not used to create reports per se but rather assist in building reports. For ex, you want to make use of certain property to derive any of the dimension members in one of your axes, you will use EPMMemberProperty. Similary, if you want to override members in any axis, you will make use of EPMDimensionOverride.
    Also, EvDRE is not replacement of EPM functions. Rather, you simply create reports using report editor (drag and drop) and then make use of EPM functions to build your report. Forget EvDRE for now.
    You can protect your report to not allow users to have that Edit Report enabled for them.
    As Vadim rightly pointed out, start building some reports and then ask specific questions.
    Hope it clears your doubts.

  • ERROR creating table with dynamic SQL :-(

    Hi friends,
    I have a problem when I try to create a table using dynamic SQL.
    (Env.: Forms 6i, WinXP, Oracle 9i)
    I only want to create a table, insert data and drop the table.
    I have a user with the correct privileges (At least ....I think so), because I can to make the three actions in SQL*PLUS (CREATE TABLE, INSERT .. and DROP TABLE).
    I want to do the same in Forms using dynamic SQL...
    I've made a package with 3 procedures:
    1st to create the table, 2nd to insert data , 3rd to drop the table.
    Only the 1st fails with the error ORA-01031 (insufficient privileges).
    Here it is:
    PROCEDURE PRO_DM_CreaTabla(pe_nombre_tabla VARCHAR2) IS
    id_cursor INTEGER;
    ls_sentencia VARCHAR2(500);
    v_dummy integer;
    BEGIN
    id_cursor := DBMS_SQL.OPEN_CURSOR;
    ls_sentencia := 'CREATE TABLE '||pe_nombre_tabla||' ( campo1 VARCHAR2(100), campo2 VARCHAR2(100), campo3 VARCHAR2(100),campo4 VARCHAR2(100))';
    DBMS_SQL.PARSE(id_cursor, ls_sentencia, dbms_sql.NATIVE);
    v_dummy := dbms_sql.execute(id_cursor);
    DBMS_SQL.CLOSE_CURSOR(id_cursor);
    END;
    The DROP_table procedure is exactly the same as this (with the difference of the 'CREATE' sentence, where I have a DROP sentence)... then.. why the DROP procedure works?... and.. why this CREATE procedure doesn't work?
    Any ideas?
    Thanks a lot.
    Jose.

    From a different thread, Jose wrote:
    V_INSERT:='INSERT INTO TMP_TABLE(field1,field3,field3,field4) VALUES (1,2,3,4)';
    Forms_DDL(V_INSERT);
    commit;First, try your statement in SQL Plus:
    INSERT INTO TMP_TABLE(field1,field3,field3,field4) VALUES (1,2,3,4);
    Then if that works, try doing this right after the Forms_DDL(V_INSERT);
    If not form_success then
      Message('   Insert has failed');
      Raise form_trigger_failure;
    Else
      Forms_DDL('COMMIT');
    End if;

  • How to create a table with events in smartforms?

    How to create a table with events view in smartforms?
    It doesn't like general table with header, main area and footer.
    for example:
    in smartforms: LE_SHP_DELNOTE
    table name is TABLEITEM(Delivery items table)

    Vel wrote:
    I am creating XML file using DBMS_XMLGEN package. This XML file will contain data from two different database tables. So I am creating temporary table in the PL/SQL procedure to have the data from these different tables in a single temporary table.
    Please find the below Dynamic SQL statements that i'm using for create the temp table and inserting the data into it.
    Before insert the V_NAME filed, i will be appending a VARCHAR field to the original data.
    EXECUTE IMMEDIATE 'CREATE TABLE TEMP_TABLE (UNIQUE_KEY NUMBER , FILE_NAME VARCHAR2(1000), LAST_DATE DATE)';
    EXECUTE IMMEDIATE 'INSERT INTO TEMP_TABLE values (SEQUENCE.nextval,:1,:2)' USING V_NAME,vLastDate;What exactly i need is to eliminate the INSERT portion of it,Since i have to insert more 90,000 rows into it. Is there way to have the temp table created with data in it along with the sequence value as well.
    I'm using Oracle 10.2.0.4 version.
    Edited by: 903948 on Dec 22, 2011 10:58 PMWhat you need to do to eliminate the INSERT statement is to -- as already suggested by others - eliminate the temporary table. You don't need it. It is just necessary overhead. Please explain why you (apparently) believe that the suggestion of a view will not meet your requirements.

  • Writing to a temp table in a stored procedure with dynamic sql

    Hi
    I am writing into a temp table with dynamic sql:
    select coloum_name into #temp_table from
    +
    @DestinationDBName+'.information_schema.tables
    and then I am trying to use #temp_table in the procedure:
    select coloum_name into #anotherTable from #temp_table
    but I am getting an error that #temp_table is not recognized.
    Can a temp table not be used in dynamic sql ?
    How can I overcome this problem ?

    Temp Table Can used easily in Dynamic Query in SQL Server and here is small Exmaple you can check it and do like it 
    CREATE PROC test
    AS
    BEGIN
    CREATE TABLE #T1 
    (ID  int , NAME Nvarchar(50))
    CREATE TABLE #T2 
    (ID  int , NAME Nvarchar(50))
    DECLARE @SQL NVARCHAR(MAX)='Insert into #T1 
    SELECT database_id , Name FROM Sys.Databases
    Insert into #T2 Select ID , Name from  #T1 '
    EXEC SP_ExecuteSQL @SQL
    SELECT * FROM #T2
    DROP TABLE #T1
    DROP TABLE #T2
    END
    Exec Test
    If you found My reply is helpful for you please vote me 
    thanks
    Mustafa EL-Masry
    Principle Database Administrator & DB Analyst
    SQL Server MCTS-MCITP
    M| +966 54 399 0968
    MostafaElmasry.Wordpress.Com

  • How to create a linked server to SQL in Oracle?

    I am able to create a linked server to Oracle in SQL.. But I do not know the steps to create a linked server too SQL in Oracle.
    How to create a linked server to SQL in Oracle? After creating the linked server to SQL, I would like to create triggers in Oracle DB to insert records into SQL DB.

    There are 2 products in Oracle you can use to link to a MS SQl Server. The first one is for free and it is called Database Gateway for ODBC. With a suitable 3rd party ODBC driver you can connect to any foreign database. The second gateway is our commercial gateway and it is called Oracle Database Gateway for MS SQL Server. It is designed for MS SQl Server connections and more powerful then Dg4ODBC. It know how to map a lot of Oracle functions to SQL Server equivalents and you can also use it to directly call SQL Server procedures or functions. This dedicated SQL server gateway is also able to participate in distributed transactions.
    But again, this is a commercial gateway and you have to purchase a license for that second gateway, the Database Gateway for MS SQl Server.
    - Klaus

Maybe you are looking for

  • Free goods in delivery proble

    Hi sap guru's here is one delivery issue--- in sales order we determined under grouping for free goods determination problem is--- free goods are appearing in sales order but not displaying in delivery type all other materials are displaying except f

  • IPod stuck on folder with exclamation point

    My iPod suddenly stopped working and started showing me the apple logo and the folder with the exclamation point over and over again. I have uninstalled all software, reinstalled, followed everything in the trouble-shooting section on this site. I ha

  • Regrading standby database in standard edition

    hi gurus i m facing problem in configuring standby database in standard edition windows 2008 . os-windows 2008 standard oracle 11gr2 i have copied files from primary n copied it to same location on standby...at that time database was in noarchivelog

  • FX5900U-VTD256 and Video In

    This card allows me to attach a VCR to it, and the drivers are installed.  Is there a utility that will allow me to watch the output from my video recorder?  I haven't found anything on the MSI CDs.

  • *Error executing SSIS Package from BPC 5.1*

    All - I'm trying to execute a perfectly working SSIS package from BPC 5.1. When I execute the package it instantly completes executing (Failure) with nothin written to the Log file. After doing further analysis, we have found the root cause to be "Se