Commit inside stored procedure

If you call a procedure from another procedure and issue COMMIT, then you commit not just inner stored procedure, but also outside procedure. Am I right? Can we make SP smarter and commit only statement in inner SP?

But bear in mind that a rollback will have a similar effect. A rollback of parent transaction will not undo the work done in the autonomous transaction. That might be a issue to watch out for if you wanted to undo all the changes in the event of an error.

Similar Messages

  • Problem in package run inside stored procedure

    i have ssis package to import data from excel to database.
    package is running correctly inside BIDS.
    but when i run package under stored procedure it is giving error :
    Error:   Code: 0xC0014023
       Source: loop sheets in excel
       Description: The GetEnumerator method of the ForEach Enumerator has failed with error 0x80040E21 "(null)". This occurs when the ForEach Enumerator cannot enumerate.

    Hi BI_DEV_19,
    Does the package connects with network resources? If so, try set the job step to run under a proxy account that is created based on a domain account. In BIDS, the package runs under the Windows account that you log onto the operating system.
    The error message “The GetEnumerator method of the ForEach Enumerator has failed with error 0x80040E21” may occur because the ADODB.dll file is corrupted or missing.  You can check whether the ADODB.dll exists in the following folder:
    C:\program files (x86)\Microsoft.NET\Primary Interop Assemblies
    In this situation, you can back up the existing ADODB.dll file, and copy one from another machine to this server.
    Regards,
    Mike Yin
    TechNet Community Support

  • Program does not break at breakpoint inside stored procedure

    I am using VS 2013 and SQL Server 2012 calling a stored procedure from a C# program. I have a breakpoint set inside the stored procedure, however execution does not stop on it. When my program is running, the breakpoint is hollow (not solid red) and the
    tool tip reads "the breakpoint will not currently be hit. No symbols have been loaded for this document".
    I built my app in debug mode and checked "SQL debugging" in the debug tab.
    Any idea as to what would cause my breakpoint to not work?
    Thanks!
    -A

    Hi achalk,
    When debugging SQL Server stored procedure in Visual Studio 2013, please make sure that Application Debugging is selected in "SQL Server Object Explorer", otherwise you will not be able to step into T-SQL.
    There are similar articles for your reference.
    Debug SQL Server 2012 Stored Procedure in Visual Studio 2013, Step by Step
    http://database.ca/blog.aspx?blogid=10
    How to debug SQL Server T-SQL in Visual Studio 2012
    http://stackoverflow.com/questions/12016417/how-to-debug-sql-server-t-sql-in-visual-studio-2012
    Thanks,
    Lydia Zhang
    If you have any feedback on our support, please click
    here.
    Lydia Zhang
    TechNet Community Support

  • Index in Query inside Stored procedure

    How to put a index on Select query inside a stored procedure.Please help me on below to write a index
    Coalesce ((select sum (ICD.mAmount)
    from ItemCommonData ICD (Index(PK_ItemCommonData))
    Join ItemsInBundle IIBun on
    (ICD.iBundleDocId = IIBun.iBundleDocId) and
    (ICD.iDocId = IIBun.iDocId)
    Join ItemsInBlock IIB (Index(ItemsInBlockbyBlockDoc)) on
    (ICD.iDocId = IIB.iDocId)
    where (Bundles.iDocId = ICD.iBundleDocId
    and IIBun.fDeleted = False
    and IIB.iBlockId = iBlockId)),

    Are you migrating to Oracle SQL and PL/SQL?
    Anyway, you don't define an Index on the fly in Oracle. You create them ahead of time on the table. You can use hints to manipulate the query into using a certain execution path.

  • Disconnected rowset CachedRowSet from a select inside stored procedure?

    Hello everyone
    I am using CachedRowSet returning it from a parameterised select statement and it works fine.
    If I put the same select statement into a simple read-only stored procedure then I get this exception: "A result set was generated for update".
    I am not trying to update the rowset in my code.
    I tried to make the CachedRowSet to be read-only but it does not help, same error.
    Question 1 : can a stored procedure returning a single result-set be called to populate a read-only CachedRowSet? (in a similar fashion to a CallableStatement prepareCall method with input/output parameters).
    Question 2: in general is using CachedRowSet, WebRowSet, FilteredRowSet (disconnected) and JDBCRowSet (connected) something to be encouraged for future develpment or are they deprecated, or replaced by something else/better??
    thank you very much in advance

    Thank you for the initial bite.
    This is for Microsoft SQL Server 2008 using Microsoft JDBC driver, type 4.0.
    The T-SQL stored procedure has a single select statement in it - see inside code.
    Below is the Java 6 source code (including the Java import statements, many unused at the moment), apologies for poor indendation, its a cut and paste problem.
    // start of Java code
    import java.io.*;
    import java.sql.*;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import com.microsoft.sqlserver.jdbc.*;
    import com.microsoft.sqlserver.jdbc.SQLServerDriver.*;
    import com.microsoft.sqlserver.jdbc.SQLServerDriver;
    import java.math.BigDecimal;
    import com.sun.rowset.CachedRowSetImpl;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.sql.Connection;
    import java.sql.Date;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.sql.Timestamp;
    import java.util.Calendar;
    import java.util.GregorianCalendar;
    import java.util.HashMap;
    import javax.sql.rowset.CachedRowSet;
    import javax.sql.rowset.spi.SyncProviderException;
    import javax.sql.rowset.spi.SyncResolver;
    public class JdbcRowSetTesting
    public static void main(String[] args)
      String connectionUrl =
      "jdbc:sqlserver://ABCDE-SERVER:1433;" +
       "databaseName=SecurityTransaction;integratedSecurity=false;user=somedbuser;password=somesortofpassword";
      Connection conn = null;
      Statement sqlstmt = null;
      ResultSet rs = null;
      CachedRowSet crs = null;
       try
      conn = DriverManager.getConnection(connectionUrl);
      System.out.println("inside try block, connected");
      conn.setAutoCommit(false);
      crs = new CachedRowSetImpl();
      crs.setUrl(connectionUrl);
      crs.setReadOnly(true);
      crs.setType(ResultSet.TYPE_FORWARD_ONLY);
      crs.setConcurrency(ResultSet.CONCUR_READ_ONLY);
      System.out.println("inside try block, connected to CachedRowSet URL"); 
    // this works fine:
      crs.setCommand("select ADDRESSID, COUNTRY, POSTCODE, STATE, ADDRESS1, ADDRESS2, ADDRESS3, ADDRESS4, CREATEDBY, CREATEDDATE, UPDATEDBY, UPDATEDDATE from dbo.address where ADDRESSID > ?;");
    -- this does not work - the SP has  the same SELECT as above inside it:
      crs.setCommand("{ call dbo.p_testCachedJDBCRowSet (?) }");
      crs.setInt(1, 10);
      crs.execute();
       while (crs.next())
      System.out.println("" + crs.getInt("ADDRESSID") + " " +
      crs.getString("ADDRESS1"));
       catch (Exception e)
      System.out.println("inside catch block, calling Exception printStackTrace(); method now:");
      e.printStackTrace();
       finally
      System.out.println("inside finally block");
       if (rs != null) try { rs.close(); } catch(Exception e) { e.printStackTrace(); }
       if (sqlstmt != null) try { sqlstmt.close(); } catch(Exception e) { e.printStackTrace(); }
       if (conn != null) try { conn.close(); } catch(Exception e) { e.printStackTrace(); }
    return;
    // end of Java source code

  • Commit inside the procedure..

    Hi,
    I have a 3 procedure, which conatain the INSERT, MERGE and then UPDATE.
    I need to put a COMMIT, inside the every procedure. if i leave the commit, when it will be committed.
    Please explain.
    -Sathya

    > I have a 3 procedure, which conatain the INSERT,
    MERGE and then UPDATE.
    need to put a COMMIT, inside the every procedure. if
    i leave the commit, when it will be committed.
    Generally, we can use commit at the end of the procedure and before the exception segment starts. But, since you are calling three procedures - you have to evalaute the bussiness logic of your coding. If it is stated that combination of these three procedure ultimately considered as one work. To establish that - you have to use commit inside the main block from where these three procedure is called.
    Ex:
    Procedure aaa()
       procedure x1( );  --performs some dml
       procedure x2( ); -- again perform some dml
       procedure x3( ); -- perform some final dml
      commit;   -- here you should use the commit
    exception
      when others then
         rollback;The reason is, if there is any exception between the three procedure - all the transactions will be rolled back - thus achieving it as logical unit work.
    Hope this will clear your doubt.
    Regards.
    Satyaki De.

  • How to use &APP_ID. inside stored procedure.

    Hello, I have created one stored procedure. I am calling it from my process code. I want to use so many page variables like &APP_ID. I do not want to pass it as argument. Is it possible to use those variables without passing it in to procedure.? (&page_id. and also some application level variables )
    Any help is appreciated.
    Thank you.

    Ashif:
    The APEX documentation describes in detail the various ways of referencing APEX session state.
    http://download.oracle.com/docs/cd/E10513_01/doc/appdev.310/e10499/concept.htm#BEICHBBG
    Local variables declared in your process block are not available in APEX' session state. Hence you cannot refence such variables in a stored procedure.
    Varad

  • Creating tables inside stored procedures

    is there a limitation as of how many tables i can cerate inside my stored proc using:
    execute immediate('CREATE TABLE xxx AS select * from yyy.... ?
    i have a stored proc that creates couple tables with the method shown above. but the compiler complains for the second create table zzz as select * from .... any idea why?
    I am attaching my procedure just in case:
    CREATE OR REPLACE
    procedure retail_cif_prep as
    begin
    begin
    execute immediate('drop table cif_retail');
    execute immediate('drop table cif_retail_wrong_ccsno');
    exception
    when others then
    null; -- or log errors other than -942 (table doesn't exist)
    end;
    execute immediate('CREATE TABLE cif_retail AS select * from cst where cstfnflag=1 and cstdatoc!=''00000000'' order by cstno');
    execute immediate('CREATE UNIQUE INDEX cif_retail_clustered ON cif_retail(CSTNO)');
    delete from cif_retail where CSTNAM='';
    execute immediate('CREATE TABLE cif_retail_wrong_ccsno AS select * from cif_retail where cstccsno not in (100, 110, 130, 900)');
    delete from cif_retail where CSTNO in (select CSTNO from if_retail_wrong_ccsno);
    end;

    Agree with 3360, this sort of things should be done beforehands.
    Basically what's happening is when you try and compile your procedure the delete statements are referencing your two tables, but I'm guessing these tables are yet to be created on the database and therefore the procedure won't compile without them.
    A dirty workaround is to put your delete statements inside execute immediate commands too.
    Then sit back, make a cup of coffee and have a good think about why on earth you are writing such poor code.

  • Privilege error while running Create Table Script inside Stored Procedure.

    Hello All,
    I have Oracle 10G server and SQL Developer Client,
    I have One User with Appropriate Rights, Login with that user from SQL Developer(client),
    Within my Procedure, Dynamic SQL script is like If I pass in a TABLE NAME as parameter, It Creates that table, but now problem is It throws an error for Privilege.
    Where as if I Execute Create table script outside the procedure(as Normal SQL), it executes Ok, but why it throws Privilege error within procedure ?
    Whether any extra Rights needed for this user to execute such Create Table Dynamic SQL?
    Please Help.
    Thanks,
    j@y

    Elic
    Thanks a lot dude...
    It works now,
    regards,
    j@y

  • Date & hour in stored procedure

    create or replace PROCEDURE library_portal_home(ldt portal_home_non_login_log.logdatetime%TYPE,   COT portal_home_non_login_log.counter%TYPE) IS
    lv_count NUMBER;
    BEGIN
      SELECT COUNT(1)
      INTO lv_count
      FROM portal_home_non_login_log
      WHERE to_date(logdatetime,   'dd-mon-yyyy hh24') = to_date(sysdate,   'dd-mon-yyyy hh24');
      IF lv_count > 0 THEN
        UPDATE portal_home_non_login_log
        SET counter = counter + 1
        WHERE to_date(logdatetime,   'dd-mon-yyyy hh24') = to_date(sysdate,   'dd-mon-yyyy hh24');
      ELSE
        INSERT
        INTO portal_home_non_login_log(logdatetime,   counter)
        VALUES(to_date(sysdate,   'dd-mon-yyyy hh24'),   1);
        DBMS_OUTPUT.PUT_LINE('FIRST NEW RECORD IS ADDED......!');
      END IF;
      COMMIT;
    END;Result
    ================
    LOGDATETIME COUNTER
    06-JUL-07      4I have created a procedure which will stored the date and also the counter.
    How do I stored hour together with the date ?
    Which part of my coding should I change such that
    when I run the procedure,the LOGDATETIME
    will have date plus the hour of time.
    E.g. Result 2 (below).
    Result 2
    =======================
    LOGDATETIME COUNTER
    06-JUL-07 13      4
    06-JUL-07 14      9
    06-JUL-07 15      3
    06-JUL-07-16      4

    There are a couple of things wrong in this procedure:
    - A select count(*) to do a check for a value is not the most efficient way. If you suspect more updates than inserts, you could do the update and check SQL%ROWCOUNT for being 0 to do an insert. Or better yet, use "merge" as Nicolas suggested.
    - Your input variables are named different than what is used in your procedure.
    - Your counter input variable is not used and can be removed
    - A commit inside a procedure is generally not recommended, because it makes it less reusable. Ideally you would let the caller decide about how a transaction is defined.
    - As already said, a date has a time component, you just need to truncate or round it to get date + hours without minutes and seconds.
    See this example:
    SQL> create table portal_home_non_login_log
      2  ( logdatetime date
      3  , counter     number
      4  )
      5  /
    Tabel is aangemaakt.
    SQL> create or replace procedure library_portal_home
      2  ( ldt portal_home_non_login_log.logdatetime%type
      3  , cot portal_home_non_login_log.counter%type
      4  ) is
      5  lv_count number;
      6  begin
      7  select count(1)
      8  into lv_count
      9  from portal_home_non_login_log
    10  where trunc(logdatetime) = trunc(sysdate);
    11
    12  if lv_count > 0 then
    13
    14  update portal_home_non_login_log
    15  set counter = counter + 1
    16  where trunc(logdatetime) = trunc(sysdate);
    17  else
    18  insert
    19  into portal_home_non_login_log(logdatetime, counter)
    20  values(sysdate, 1);
    21  dbms_output.put_line('FIRST NEW RECORD IS ADDED......!');
    22  end if;
    23
    24  end;
    25  /
    Procedure is aangemaakt.
    SQL> exec library_portal_home(sysdate,5)
    FIRST NEW RECORD IS ADDED......!
    PL/SQL-procedure is geslaagd.
    SQL> exec library_portal_home(sysdate-1/48,5)
    PL/SQL-procedure is geslaagd.
    SQL> exec library_portal_home(sysdate-1/24,5)
    PL/SQL-procedure is geslaagd.
    SQL> exec library_portal_home(sysdate-1/6,5)
    PL/SQL-procedure is geslaagd.
    SQL> select * from portal_home_non_login_log
      2  /
    LOGDATETIME                                        COUNTER
    09-07-2007 10:22:47                                      4
    1 rij is geselecteerd.
    SQL> rollback
      2  /
    Rollback is voltooid.
    SQL> create or replace procedure library_portal_home
      2  ( p_logdatetime in portal_home_non_login_log.logdatetime%type
      3  )
      4  is
      5  begin
      6    update portal_home_non_login_log
      7       set counter = counter + 1
      8     where trunc(logdatetime,'hh24') = trunc(p_logdatetime,'hh24')
      9    ;
    10    if sql%rowcount = 0
    11    then
    12      insert into portal_home_non_login_log
    13      ( logdatetime
    14      , counter
    15      )
    16      values
    17      ( trunc(p_logdatetime,'hh24')
    18      , 1
    19      );
    20    end if;
    21  end;
    22  /
    Procedure is aangemaakt.
    SQL> exec library_portal_home(sysdate)
    PL/SQL-procedure is geslaagd.
    SQL> exec library_portal_home(sysdate-1/48)
    PL/SQL-procedure is geslaagd.
    SQL> exec library_portal_home(sysdate-1/24)
    PL/SQL-procedure is geslaagd.
    SQL> exec library_portal_home(sysdate-1/6)
    PL/SQL-procedure is geslaagd.
    SQL> select * from portal_home_non_login_log
      2  /
    LOGDATETIME                                        COUNTER
    09-07-2007 10:00:00                                      1
    09-07-2007 09:00:00                                      2
    09-07-2007 06:00:00                                      1
    3 rijen zijn geselecteerd.
    SQL> rollback
      2  /
    Rollback is voltooid.
    SQL> create or replace procedure library_portal_home
      2  ( p_logdatetime in portal_home_non_login_log.logdatetime%type
      3  )
      4  is
      5  begin
      6    merge into portal_home_non_login_log
      7    using ( select p_logdatetime ldt from dual )
      8       on ( trunc(logdatetime,'hh24') = trunc(ldt,'hh24') )
      9     when matched then
    10          update set counter = counter + 1
    11     when not matched then
    12          insert (logdatetime,counter) values (trunc(ldt,'hh24'),1)
    13    ;
    14  end;
    15  /
    Procedure is aangemaakt.
    SQL> exec library_portal_home(sysdate)
    PL/SQL-procedure is geslaagd.
    SQL> exec library_portal_home(sysdate-1/48)
    PL/SQL-procedure is geslaagd.
    SQL> exec library_portal_home(sysdate-1/24)
    PL/SQL-procedure is geslaagd.
    SQL> exec library_portal_home(sysdate-1/6)
    PL/SQL-procedure is geslaagd.
    SQL> select * from portal_home_non_login_log
      2  /
    LOGDATETIME                                        COUNTER
    09-07-2007 10:00:00                                      1
    09-07-2007 09:00:00                                      2
    09-07-2007 06:00:00                                      1
    3 rijen zijn geselecteerd.Regards,
    Rob.

  • Multiple stored procedures using JDBC Adopter, Synchronous call

    Hello Guys,
    This is kind of different scenario,
    Here is the scenario (SQL Server -> XI -> Legacy)
    1.I want to trigger stored procedure (from XI to)
    2.Inside the stored procedure we are going to have multiple stored procedures.
    -Inside stored procedures
    SP1 -> It supposed to select the data from interface control table, if that is success
    SP2 -> Call some other stored procedures which can be select/insert/delete from different tables most of the cases it would be select, if that is success
         It should give results back (Response) to XI and with some output parameters like (status message, etc…)
    Next step I want send those results to target system which is legacy. If that is success
    Next step I should update entry in the Interface control table(which is in SQL Server) with success entry like (success message, current date, current time, interface name, username.) 
         If it fails any stage like while selecting data from interface control table which is SP1/ SP2 It should give error message back to XI(output parameters). XI is going to send Alerts/Mails to respective interface owners.
    This is my scenario can anybody help me on this what needs to be done to implement this scenario.

    Hi Murali,
    Anyway , altimately you are going to call one stored procedure and going to get one output. So it will not be a problem I think.
    Anyway it is required to introduce BPM here.
    <i>Next step I want send those results to target system which is legacy. If that is success</i>
    >>>You can make sure that message is recieved by legacy system. Because legacy systems like File systems will not support Application Acknowledgement. So here you can go with Transport Acknowledgement.
    From where will get Success messages like (current date etc) are you planning to take XI system date.. If so you can get this. And you can send the message to SQL.
    <i>If it fails any stage like while selecting data from interface control table which is SP1/ SP2 It should give error message back to XI(output parameters). XI is going to send Alerts/Mails to respective interface owners.</i>
    >>>For application errors like SP2 error etc, you need to get the Error Response from stored procedure itsel.
    Second option is you can go with Adapter Alerting, whenever any error in the Sender JDBC adapter.
    Anyway design/requirement should be perfect, before start the process here...
    Regards,
    Moorthy

  • How to write stored procedure to spool data into file

    Hi ,
    We get differnt excel sheets of differnt products.
    We upload data from excel sheet to database . After uploading data , I run Preprossor (sql script) to check the data
    This preprocessor script contains several select statements that query different tables in database .the output is spooled into a cvs file .
    I need to change this script into a stored procedure and spool the output to cvs file.
    File spooling should be done inside the stored procedure so that if I call this stored procedure from java program ,or any concurrent program,its output is .cvs file and in parameter should be productname.
    But inside the stored procedure , we cannot spool the data to some .cvs file . Is any way.I do not want to spool to file when calling.It should be inside stored procedure.
    Or do I need to create a table and insert all the select statements output into it .
    Here is the sample preprocessor script.
    spool Graco_Product.csv
    set head off
    set feedback off
    set Pagesize 100
    SELECT '1. EVERY ASSEMBLY GROUP ADDED IN sys_PRODUCT TABLE MUST HAVE AT LEAST ONE ITEM IN WOC_ASSEMBLY_ITEM'
         FROM DUAL;
    SELECT 'ASSEMBLY_GROUP_NAME'
         FROM DUAL;
    SELECT
         assembly_group_name
         FROM association
         WHERE product_model_name = 'Graco_Product'
         AND assembly_group_name NOT IN (SELECT DISTINCT assembly_group_name FROM woc_assembly_item);
    SELECT '2. A RULE SHOULD HAVE AT LEAST ONE EXPRESSION FOR ITS ACTION SIDE.'
         FROM DUAL;
    SELECT 'RELATION_ID , RELATION_TYPE'
         FROM DUAL;
    SELECT wr.Relation_ID                    ||','||
         wr.Relation_Type                    
         FROM WOC_Relation wr
         WHERE NOT EXISTS (SELECT 'X' FROM WOC_Relation_Expression wre
    WHERE wre.Relation_Side = 'Action'
    AND wr.Relation_ID = wre.Relation_ID)
         AND wr.Relation_Type NOT IN ( 'Rule Warning','Rule Resource','Rule Default');
    SELECT '3. PROPERTIES USED IN RULES SHOULD EXIST IN WOC_PROPERTY_MASTER -- EXP_LHS_VALUE'
         FROM DUAL;
    SELECT
         'RELATION_OWNER,EXP_LHS_OPERAND,RELATION_SIDE,RELATION_ID,EXP_LHS_VALUE,RELATION_TYPE'     
         FROM DUAL;
    SELECT
         b.relation_owner               ||','||
         a.exp_lhs_operand               ||','||
         a.relation_side                    ||','||
         a.relation_id                    ||','||
         a.exp_lhs_value                    ||','||
         b.relation_type
         FROM woc_relation_expression a, woc_relation b
         WHERE a.exp_lhs_value IS NOT NULL
         AND a.exp_lhs_value_type = 'Property'
         AND a.exp_lhs_value NOT IN (SELECT property_name FROM woc_property)
         AND b.product_model_name = 'Graco_Product'
         AND a.relation_id = b.relation_id;
    SELECT '--------------------------------------------------------------------------------'
    from dual;
    spool off
    set head on
    set feedback on

    High level description
    Full documentation
    Note that the UTL_ and DBMS_ packages are all covered in the PL/SQL Packages and Types Reference.
    You may also want to read up on the CREATE DIRECTORY statement, which lets you refer to an actual OS directory (which you create separately) via a database object.

  • DDL statement/s in stored procedures (FUNCTION)

    Hello all,
    I was trying to create a small function that tests keywords on the basis of successful/failed table creation. If a table can be created with a keyword as identifier, it is a non-reserved keyword, if table creation fails, it is a reserved keyword:
    CREATE OR REPLACE FUNCTION createTableForKeyword (keyword VARCHAR) RETURN BOOLEAN IS
    BEGIN
    CREATE TABLE keyword (x NUMBER);
    -- if no exception occurred, table creation succeeded
    DROP TABLE keyword; drop it
    RETURN FALSE; -- FALSE means non-reserved
    EXCEPTION
    WHEN OTHERS THEN
    -- if exception occurred, table creation failed
    RETURN TRUE; -- TRUE means reserved
    END createTableForKeyword;
    This would have been my first PL/SQL program, but I get the following error:
    PLS-00103: Found symbol "CREATE" when expecting one of:
    begin case declare exit ................
    .............. merge pipe
    I had to translate the error message from German, but it should suffice. Obviously DDL statements in functions are not allowed. How do I solve my problem then, given a table that has one column containing the keyword?:
    CREATE TABLE Keywords (keyword VARCHAR(30));
    I was looking too call this function from a loop, but how would I do this without a function? How do I capture table creation fails without exceptions in functions?
    TIA
    Karsten

    To run DDL inside stored procedure you must use Dynamic SQL. Use EXECUTE IMMEDIATE
    To see if a word is a reserved word just query V$RESERVED_WORDS
    Thanks,
    Karthick.

  • Autocommit in Stored procedures

    Hi all!
    Can we set the autocommit variable in a stored procedure? if yes, how?
    regards,
    Rajat Aggarwal

    No. Autocommit can be turned OFF at the client or connection level, and that is the only thing you should do to it. It can be useful to set it ON when connecting to Microsoft SQL Server databases.
    Don't commit in stored procedures either, let the client commit the procedure changes, then you can write procedures that can be called together within a transaction.

  • Conversion failed when converting the nvarchar value to data type int when returning nvarchar(max) from stored procedure

    Thank you for your help!!! 
    I've created a stored procedure to return results as xml.  I'm having trouble figuring out why I'm getting the error message "Conversion failed when converting the nvarchar value '<tr>.....'
    to data type int.    It seems like the system doesn't know that I'm returning a string... Or, I'm doing something that I just don't see.
    ALTER PROCEDURE [dbo].[p_getTestResults]
    @xml NVARCHAR(MAX) OUTPUT
    AS
    BEGIN
    CREATE TABLE #Temp
    [TestNameId] int,
    [MaxTestDate] [DateTime],
    [Name] [nvarchar](50),
    [Duration] [varchar](10)
    DECLARE @body NVARCHAR(MAX)
    ;WITH T1 AS
    SELECT DISTINCT
    Test.TestNameId
    , replace(str(Test.TotalTime/3600,len(ltrim(Test.TotalTime/3600))+abs(sign(Test.TotalTime/359999)-1)) + ':' + str((Test.TotalTime/60)%60,2)+':' + str(Test.TotalTime%60,2),' ','0') as Duration
    ,MaxTestDate = MAX(TestDate) OVER (PARTITION BY TM.TestNameId)
    ,TestDate
    ,TM.Name
    ,Test.TotalTime
    ,RowId = ROW_NUMBER() OVER
    PARTITION BY
    TM.TestNameId
    ORDER BY
    TestDate DESC
    FROM
    Test
    inner join TestName TM on Test.TestNameID = TM.TestNameID
    where not Test.TestNameID in (24,25,26,27)
    INSERT INTO #Temp
    SELECT
    T1.TestNameId
    ,T1.MaxTestDate
    ,T1.[Name]
    ,T1.Duration
    FROM
    T1
    WHERE
    T1.RowId = 1
    ORDER BY
    T1.TestNameId
    SET @body ='<html><body><H3>TEST RESULTS INFO</H3>
    <table border = 1>
    <tr>
    <th> TestNameId </th> <th> MaxTestDate </th> <th> Name </th> <th> Duration </th></tr>'
    SET @xml = CAST((
    SELECT CAST(TestNameId AS NVARCHAR(4)) as 'td'
    , CAST([MaxTestDate] AS NVARCHAR(11)) AS 'td'
    , [Name] AS 'td'
    , CAST([Duration] AS NVARCHAR(10)) AS 'td'
    FROM #Temp
    ORDER BY TestNameId
    FOR XML PATH('tr'), ELEMENTS ) AS NVARCHAR(MAX))
    SET @body = @body + @xml +'</table></body></html>'
    DROP TABLE #Temp
    RETURN @xml
    END
    closl

    Your dont need RETURN inside SP as you've declared @xml already as an OUTPUT parameter. Also you can RETURN only integer values using RETURN statement inside stored procedure as that's default return type of SP.
    so just remove RETURN statement and it would work fine
    To retrieve value outside you need to invoke it as below
    DECLARE @ret nvarchar(max)
    EXEC dbo.[P_gettestresults] @ret OUT
    SELECT @ret
    Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

Maybe you are looking for