Stored Procedure is very slow

I have a stored procedure that is very slow and would like more efficient SQL.  I want to get a selection of data put into a @SearchTbl that I send elsewhere for further manipulation.  I do these in two parts.  First, if the sending program
sends a specific @UserName, @EntryTime, and/or @Type, I get all entries that meet these conditions.  If the user does not send an entrytime (If NULL), I get the latest entries from the @SearchTbl for each unique combination of certain variables.  Is
there a way to do both in one step?
Any suggestions on how to make these steps below faster?
CREATE PROCEDURE MyProcedure
@UserName nvarchar(255) = NULL, @EntryTime datetime = NULL, @Type nvarchar(255) = NULL
AS
DECLARE @SQL nvarchar(4000)
DECLARE @whereAdd nvarchar(4000)
DECLARE @SearchTbl tempSearchTbl_tbltype
DECLARE @TvuTbl TVU_tbltype
DECLARE @t int
DECLARE @tempCt int
DECLARE @narCt int
DECLARE @n int
IF @Type IS NOT NULL AND @UserName IS NOT NULL
BEGIN
SET @whereAdd = ' WHERE Type = @Type AND UserName = @UserName'
END
IF @Type IS NOT NULL AND @UserName IS NULL
BEGIN
SET @whereAdd = ' WHERE Type = @Type'
END
IF @Type IS NULL AND @UserName IS NOT NULL
BEGIN
SET @whereAdd = ' WHERE UserName = @UserName'
END
SET @SQL = 'SELECT CName, UserName, Type, Address, CardNum, CText,
EntryTime, Var1, Var2, Var3 FROM PTable' + @whereAdd
IF @Type IS NULL AND @UserName IS NULL
BEGIN
SET @SQL = 'SELECT CName, UserName, Type, Address, CardNum, CText,
EntryTime, Var1, Var2, Var3 FROM PTable'
END
INSERT INTO @SearchTbl (CName, UserName, Type, Address, CardNum, CText,
EntryTime, Var1, Var2, Var3)
EXEC sp_executesql @SQL,
N'@UserName nvarchar(255), @Type nvarchar(255)'
@UserName, @Type
GetLatestLoop:
IF @EntryTime IS NULL
BEGIN
With CTE As (SELECT CName, Type, CText, CardNum,
Row_Number() OVER(Partition By CName, Type, CardNum, Type ORDER BY EntryTime Desc) AS rn
FROM @SearchTbl)
DELETE FROM CTE WHERE rn > 1
END
Gina

Looks like this would suffice
CREATE PROCEDURE MyProcedure
@UserName nvarchar(255) = NULL, @EntryTime datetime = NULL, @Type nvarchar(255) = NULL
AS
DECLARE @SQL nvarchar(4000)
DECLARE @whereAdd nvarchar(4000)
DECLARE @SearchTbl tempSearchTbl_tbltype
DECLARE @TvuTbl TVU_tbltype
DECLARE @t int
DECLARE @tempCt int
DECLARE @narCt int
DECLARE @n int
SET @whereAdd = ''
IF @Type IS NOT NULL
BEGIN
SET @whereAdd = @whereAdd + ' AND Type = @Type'
END
IF @UserName IS NOT NULL
BEGIN
SET @whereAdd = @whereAdd + ' AND UserName = @UserName'
END
IF @EntryTime IS NOT NULL
BEGIN
SET @whereAdd = @whereAdd + ' AND EntryTime = @EntryTime'
END
ELSE
BEGIN
SET @whereAdd = @whereAdd + 'AND NOT EXISTS ( SELECT 1
FROM PTable
WHERE CName = p.CName
AND Type = p.Type
AND CardNum = p.CardNum
AND EntryTime > t.EntryTime
END
SET @SQL = 'SELECT CName, UserName, Type, Address, CardNum, CText,
EntryTime, Var1, Var2, Var3 FROM PTable p
WHERE 1 = 1' + @whereAdd
INSERT INTO @SearchTbl (CName, UserName, Type, Address, CardNum, CText,
EntryTime, Var1, Var2, Var3)
EXEC sp_executesql @SQL,
N'@UserName nvarchar(255), @Type nvarchar(255),@EntryTime datetime'
@UserName, @Type,@EntryTime
END
Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

Similar Messages

  • SQL server 2000 Procedure executing very slower in SQL 2012

     
    Hi,
    I've migrated my database from SQL 2000 to SQL 2012 using SQL2008 as intermediate. After migration, I found that one of my procedure is timing out from web site. When I run that procedure in Management Studio, it takes 42 seconds to display result. The same
    query is executed in 3 seconds in SQL 2000 version (in first run it takes 10 seconds in SQL 2000 and second run it took 3 seconds only). But in SQL 2012 second and third time also it took 36 seconds. Can anyone explain why the query takes longer time instead
    of less time after the upgrade? 
    Our prod deployment date is approaching so any quick help is appreciated. 
    Thanks in advance.

    You need to compare the execution plans of queries running in 2000 and 2012 to pin point why there is a difference.
    However, have you made sure that you have reindexed the indexes and updated the stats and you still see the difference? If not, please do that and test again.
    Could you post the execution plans?
    Also read this -
    http://blogs.msdn.com/b/psssql/archive/2015/01/30/frequently-used-knobs-to-tune-a-busy-sql-server.aspx
    Regards, Ashwin Menon My Blog - http:\\sqllearnings.com

  • Storing blobs is very slow

    I am using the following code to store a blob in a database:
    PreparedStatement pstmt = sql.conConnection.prepareStatement(
    "UPDATE JAttributes SET AttributeBulky=? WHERE AttributeID=?" );
    pstmt.setBinaryStream( 1, inStream, (int) lObjectLength );
    pstmt.setInt( 2, nAttributeID );
    pstmt.executeUpdate();
    pstmt.close();
    Although this works, it is extremely slow. Does anybody know any workaround to this problem?
    null

    Also, look into the various lob settings in ODP.NET.
    I believe that by default in ODP.NET the LOB will be fetched in separate roundtrips but you can change this my messing with certain properties or using certain methods - apologies, a bit imprecise.
    If you have a network issue then doing more roundtrips than you need to is just going to exacerbate the situation.
    Trace the session - if it's networking or roundtrips you should see symptoms of it in a 10046 trace.

  • Error calling a stored procedure from C#

    Please help me!
    I'm new in .net technology.
    I have an Oracle 9i server and an application in .net C# language.
    I'm trying to call a stored procedure written in plsql.
    This is the testing procedure:
    CREATE OR REPLACE PROCEDURE TEST_PROC
    par_1 in number
    as
    begin
    insert into tbltestinput (number_col) values (par_1);
    commit;
    end;
    And the calling code is:
    OracleCommand objCmd = new OracleCommand("TEST_PROC",conn);
    objCmd.CommandType = CommandType.StoredProcedure;
    OracleParameter inPar_1 = new OracleParameter();
    inPar_1.OracleType = OracleType.Number;
    inPar_1.Direction = ParameterDirection.Input;
    inPar_1.Value = 123456;
    objCmd.Parameters.Add(inPar_1);
    objCmd.ExecuteNonQuery();
    It returns this error:
    Exception Message: ORA-06550: row 1, column 7: PLS-00306: wrong number or types of arguments in call to 'TEST_PROC' ORA-06550: row 1, column 7: PL/SQL: Statement ignored
    Exception Source: System.Data.OracleClient
    The stored procedure is very very simple to test only the call.
    Anybody can help me.
    Thanks !!!!

    Hello,
    System.Data.OracleClient == Microsoft provider for Oracle (whereas this is the Oracle Data Provider for .NET forum).
    However, the MS provider operates in Bind By Name mode, so you might try adding this to your code:
    inPar_1.ParameterName = "par_1";Perhaps that will help a bit,
    Mark

  • Database Adapter calling stored procedure with xmlDOM.DOMNODE input problem

    Hi all,
    I have been asked to do a POC on using SOA suite to generate a web-service for several database stored procedure. A few of them can be done without a fuss. But I am now stuck with a stored procedure that has input and output as xmlDOM.DOMNODE type.
    The stored procedure is very simple as below:
    procedure prc_accinquiry(request in xmlDOM.DOMNODE, response out xmlDOM.DOMNODE) is
    begin
    response := request;
    end prc_accinquiry;
    I get the following error
    Error while writing wsdl file C:/JDeveloper/mywork/ABSPOC/NetBanking/DomNodeTestDB.wsdl. Exception: WSDLException: faultCode=OTHER_ERROR: The wrapper procedure, PACK_TESTING$PRC_ACCINQUIRY, could not be found in the package, BPEL_DOMNODETESTDB, for the schema, MBTT
    Did I do something wrong? or DOMNODE is not part of supported datatype for DB Adapter stored procedure call from JDeveloper?
    The environment is SOA suite 11g 11.1.1.5 with Database 11 XE
    Thank you in advance,
    Jomphop
    Edited by: e-Teoy on 15/12/2011 19:49

    This problem can be resolved by granting execute permission on the object type to the caller. For example, if the stored procedure is in schema1 and the object type is in schema2 then you would connect as schema2 and execute
    SQL> grant execute on <object type> to schema1
    Referencing object types defined in other schemas is documented. This is the described method for accessing object types in other schemas.

  • Can we able to call .bat file from Stored procedure?

    My actual requirement is to import an csv file(where it contains a table) into oracle Database from the front end screen when the csv file location is given.
    Where in the screen (designed by dotnet) a browse option will be present and I will give the csv file location and this will be passed into stored procedure as an input parameter.
    Now I need a stored Procedure that can Import my csv file table data into Oracle database10g.
    I shoudnot use the import option present in the physical Oracle Database.
    Can any one please provide me the stored Procedure?

    NGK246 wrote:
    My actual requirement is to import an csv file(where it contains a table) into oracle Database from the front end screen when the csv file location is given.
    Where in the screen (designed by dotnet) a browse option will be present and I will give the csv file location and this will be passed into stored procedure as an input parameter.
    Now I need a stored Procedure that can Import my csv file table data into Oracle database10g.You do not seem to understand the basic concept of client-server. If you supply a file location for the server code, and that location is not on the server, how do you expect the server to access that file in that location?
    You cannot expect the server to hacks its way across the network, crack open a remote file system somewhere, and steal that file from that location.
    As the client has access to that location and file, the client needs to read that file and supply that file's content to the server. This is how the server receives a file from a client. With Oracle. With FTP. With SCP. With SFTP. With HTTP. With SMTP and file attachments to e-mails. Etc.
    This is not specific to Oracle. This is a fundamental concept. So the problem here is your ignorance of client-server and not a problem with Oracle and not a problem with PL/SQL.
    I shoudnot use the import option present in the physical Oracle Database.Not sure what this mean, but the basic statement that "+we should not use feature 123 or feature ABC of Oracle+", is invariable an utterly idiotic statement to make. Kind of like buying a car and then making the statement that groceries may not be put into the truck as the car's trunk should not be used.
    Can any one please provide me the stored Procedure?Very arrogant of you to assume that others will spend their free time writing code for you - with you copying-and-pasting that code and providing it to your employers, as your work...

  • Crystal Reports can't add stored procedure using Oracle Provider for OLE DB

    Hello,
    I am trying to bind an oracle stored procedure to a crystal report through Visual Studio 2008.
    This oracle stored procedure returns a ref cursor.
    I am using an oracle 11g database (11.2.0.2.0) .
    When I use the Oracle Provider For OLE DB driver to bind the store procedure with the report, I get the following error message:
    Description : ORA -06550 Line 1 Column 7
    PLS 00306 wrong number of types or arguments to the "Strored Procedure Name"
    But When I use the Microsoft OLE DB provider for oracle driver, I can bind the stored procedure to the report successfully .
    I cannot use the Microsoft OLE DB provider for oracle driver because it does not support the CLOB data type which I plan on having the stored procedure return once I can get everything working.
    I have tried setting PLSQLRSET = 1 IN "HKEY_LOCAL_MACHINE\SOFTWARE\KEY_OraDb11g_home1\OLEDB", but that does not seem to work either
    Any assistance would be greatly Appreciated
    My Stored procedure is very simple as the moment (I just need to get it working then I'll add more stuff). Here's what it looks like:
    CREATE OR REPLACE PACKAGE PROMO.PKG_REPORT as
    TYPE OUT_Type IS REF CURSOR;
    procedure Report_ThisReport (
    p_ThisIdField IN number,
    IO_CURSOR IN OUT OUT_Type
    end PKG_REPORT;
    CREATE OR REPLACE PACKAGE BODY PROMO.PKG_REPORT as
    procedure REPORT_ThisReport (
    p_ThisIdField IN number,
    IO_CURSOR IN OUT OUT_Type
    IS
    BEGIN
    OPEN IO_CURSOR FOR
    SELECT ThisField
    FROM ThisTable
    WHERE ThisIdField = p_ThisIdField ;
    END REPORT_ThisReport;
    end PKG_REPORT;
    Edited by: 894988 on Nov 3, 2011 2:45 PM
    Edited by: 894988 on Nov 3, 2011 2:46 PM
    Edited by: 894988 on Nov 3, 2011 2:47 PM

    It seems that some questions posted here on the XE forum are really questions about other Oracle technologies.
    Concretely, for you there is an Oracle Provider for OLE DB Forum that is active and a terrific resource for you to use.
    Oracle Provider for OLE DB
    Cheers!

  • Invoking Stored Procedure - Transform Activity

    I am attempting to invoke a PL/SQL stored procedure via the database adapter in BPEL (10.1.3.1). The stored procedure is very simple and takes 2 parameters:
    PROCEDURE log_admission(p_px_id NUMBER, p_cons_lev NUMBER) IS
    BEGIN
    UPDATE nhscont_px
    SET pat_admitted = 'Y',
    pat_admitted_date = sysdate
    WHERE pat_match_id = p_px_id;
    END;
    The BPEL flow has the following activities:
    Recieve
    Transform
    Invoke => DB Adapter, with package / procedure selected
    Reply
    I have created a variable of type: MessageType: PartnerLink: DbAdapterCall: args_in_msg.
    In the Transform activity, I have selected the inputVariable/Payload as the source, and the defined variable/Inputparameters as the destination. I have created a mapping file and mapped the variables between schemas.
    I have set the input variable of the process as the variable created above.
    When I deply and execute the process, the record does not update, although the PL/SQL is being executed. It looks like the parameters are not being passed in correctly.
    Does anyone have any ideas as to what I could be doing wrong here?
    Thanks
    Message was edited by:
    steve_macleod

    Seeing the parameters being passed in to the procedure on the invoke activity.
    Does the Invoke activity in BPEL have the values you are transforming?
    Kalidass
    http://oraclebpelindepth.blogspot.com/

  • How do I speed up firefox. It loads very slow compaired to others

    Firefox is very slow to load and slow bringing up web sites. I have cleared all stored items, still very slow
    == This happened ==
    Every time Firefox opened
    == After using the program for several months

    You can speed up Firefox by tweaking some of the '''about:config''' settings from within Firefox. Here is the [http://www.ehow.com/how_2033391_enable-pipelining-firefox.html link]

  • After installing Snow Leopard, Mail became very slow contacting provider

    With Leopard, our Mail on different Macs where very quick to contact the provider. You know what I mean, not sending or receiving the messages, I mean the connection procedure at the beginning. With Snow Leopard this procedure became very slow. Never understood why

    HI,
    Launch Mac Mail.
    From the Menu Bar, click Mail/Preferences.
    Make note of your preferences then locate this file.
    com.apple.Mail.plist
    Move that file to the Trash and restart your Mac.
    Also, try repairing disk permissions.
    Quit any open applications/programs. Launch Disk Utility. (Applications/Utilities) Select MacintoshHD in the panel on the left, select the FirstAid tab. Click: Repair Disk Permissions. When it's finished from the Menu Bar, Quit Disk Utility and restart your Mac. If you see a long list of "messages" in the permissions window, it's ok. That can be ignored. As long as you see, "Permissions Repair Complete" when it's finished... you're done. Quit Disk Utility and restart your Mac.
    And try Mac OS X - Maintenance
    Carolyn
    Message was edited by: Carolyn Samit

  • DAC task with Informatica mapping and stored procedure (very slow)

    Hello,
    We have a DAC task that launch an Informatica Workflow with a simple query and stored procedure, like this:
    SQL QUERY
    ==========================
    SELECT
    W_ACTIVITY_F.ROW_WID,
    W_AGREE_D.AGREE_NUM,
    W_PRODUCT_D.ATTRIB_51,
    W_SRVREQ_D.ATTRIB_05,
    W_ORG_DH.TOP_LVL_NAME,
    W_ORG_D.ATTRIB_06,
    W_PRODUCT_GROUPS_D.PRODUCT_LINE,
    W_PRODUCT_D.PROD_NAME
    FROM
    W_AGREE_D,
    W_SRVREQ_F,
    W_ACTIVITY_F,
    W_PRODUCT_D LEFT OUTER JOIN W_PRODUCT_GROUPS_D ON W_PRODUCT_D.PR_PROD_LN = W_PRODUCT_GROUPS_D.PRODUCT_LINE,
    W_ORG_D,
    W_SRVREQ_D,
    W_ORG_DH
    WHERE
    W_SRVREQ_F.AGREEMENT_WID = W_AGREE_D.ROW_WID AND
    W_SRVREQ_F.SR_WID = W_ACTIVITY_F.SR_WID AND
    W_SRVREQ_F.PROD_WID = W_PRODUCT_D.ROW_WID AND
    W_SRVREQ_F.ACCNT_WID = W_ORG_D.ROW_WID AND
    W_SRVREQ_F.SR_WID = W_SRVREQ_D.ROW_WID AND
    W_ORG_D.ROW_WID = W_ORG_DH.ROW_WID
    STORED PROCEDURE
    ===========================
    ConvSubProy(W_AGREE_D.AGREE_NUM,
    W_PRODUCT_D.ATTRIB_51,
    W_SRVREQ_D.ATTRIB_05,
    W_ORG_DH.TOP_LVL_NAME,
    W_ORG_D.ATTRIB_06,
    W_PRODUCT_GROUPS_D.PRODUCT_LINE,
    W_PRODUCT_D.PROD_NAME)
    The mapping is very simple:
    Source Qualifier -> Stored procedure -> Update strategy (only two ports: ROW_WID and custom column) -> Target Table
    When I launch the DAC Execution Plan the corresponding task take much time (40 minuts). But when I launch the corresponding Workflow from Informatica PowerCenter Workflow Manager this only take 50 seconds... when I see the log session for the task I can see that much time is spent on the time of the updates. For example, when DAC is running the writer updates 10000 records every 6/7 minuts, but when Workflow Manager is running thw writer updates 10000 records every 8/9 seconds.
    So, what happens (in the DAC) to that so much time difference? Is there a way to reduce the execution time when the task is launched from DAC?
    Thanks
    Best Regards
    Benjamin Tey

    Have you tried using bulk load type?
    In Workflow Manager can you open the associated task, navigate to the mapping tab and seled the target table.
    What is the value for "Target load type" and which of the following boxes are checked: Insert, Update as Update, Update as Insert, Update else Insert, Delete?

  • Improve the performance in stored procedure using sql server 2008 - esp where clause in very big table - Urgent

    Hi,
    I am looking for inputs in tuning stored procedure using sql server 2008. l am new to performance tuning in sql,plsql and oracle. currently facing issue in stored procedure - need to increase the performance by code optmization/filtering the records using where clause in larger table., the requirement is Stored procedure generate Audit Report which is accessed by approx. 10 Admin Users typically 2-3 times a day by each Admin users.
    It has got CTE ( common table expression ) which is referred 2  time within SP. This CTE is very big and fetches records from several tables without where clause. This causes several records to be fetched from DB and then needed processing. This stored procedure is running in pre prod server which has 6gb of memory and built on virtual server and the same proc ran good in prod server which has 64gb of ram with physical server (40sec). and the execution time in pre prod is 1min 9seconds which needs to be reduced upto 10secs or so will be the solution. and also the exec time differs from time to time. sometimes it is 50sec and sometimes 1min 9seconds..
    Pl provide what is the best option/practise to use where clause to filter the records and tool to be used to tune the procedure like execution plan, sql profiler?? I am using toad for sqlserver 5.7. Here I see execution plan tab available while running the SP. but when i run it throws an error. Pl help and provide inputs.
    Thanks,
    Viji

    You've asked a SQL Server question in an Oracle forum.  I'm expecting that this will get locked momentarily when a moderator drops by.
    Microsoft has its own forums for SQL Server, you'll have more luck over there.  When you do go there, however, you'll almost certainly get more help if you can pare down the problem (or at least better explain what your code is doing).  Very few people want to read hundreds of lines of code, guess what's it's supposed to do, guess what is slow, and then guess at how to improve things.  Posting query plans, the results of profiling, cutting out any code that is unnecessary to the performance problem, etc. will get you much better answers.
    Justin

  • After closing large documents (drawings) the window closes but the process runs still in the background. I open the next document, the same procedure and after dowing this several times the RAM is full the system becoms very slow. what can i do???

    after closing large documents (drawings) the window closes but the process runs still in the background. I open the next document, the same procedure and after dowing this several times the RAM is full the system becoms very slow. what can i do???

    You can always shut it down manually via the Task Manager
    (CtrlShiftEsc)...
    On Mon, Sep 1, 2014 at 3:05 PM, frank koethen <[email protected]>

  • Query slower in stored procedure(after upgrade to 16)

    Hi all,
    We are looking to upgrade our SQL Anywhere 9 database to 16. We thought version 16 is slower in update tables, but the reason of slowness are query's in stored procedures called from the trigger. One of the query's has a duration of 8 times the duration in version 9!! When I run the query in Interactive Sql(v16), they run fast like version 9. So the query runs slower in a stored procedure.
    I thought parameter sniffing, but it's not MS Sql Server. I've no idea why it was good in v9 and bad in v16. Have someone a idea?
    It's a query with subquery's in the where , a view in the from. In the view are unions. Looks not so special.
    thanks

    It may be more convenient for you to ask this question on the other forum: SAP SQL Anywhere Forum
    Preamble...
    It sometimes happens that (a) the same query will perform faster or slower in different versions because of different behaviors by the query optimizer. In most cases a minor change is necessary to restore good performance; in some rare cases, the changes are difficult.
    It also sometimes happens that (b) the same query will perform faster or slower under different operating conditions; e.g., client request (ISQL) versus inside a BEGIN block (stored procedure). Again, minor changes all that's required in most cases, sometimes otherwise.
    Details...
    In order to help, we will need more information. Two graphical plans with statistics for the same problematic query, both using V16, one captured in ISQL, and the other one captured inside the stored procedure, is the best way to pass on the information; ALL OTHER forms are inadequate, especially prose descriptions and edited snippets of code (that way lies frustration for all parties).
    There are a number of articles about graphical plans on this blog.

  • SQL*Loader with Stored Procedure slow

    I have a situation where if SQL*Loader is running then stored procedures returning cursors are excruciatingly slow (about 3 minutes) if the same stored procedure is run via SQL statements it runs fine. The stored procedures also run fine if SQL*Loader is not running. Has anyone seen this before, any thoughts?
    Thanks,
    ed

    My query was:
    SELECT *
    FROM scheme.table@as400 a
    WHERE a.vlvalr = to_char(p_vlvalr)
    and a.vlvals = to_char(p_vlvals);
    Without the to_char! When I add the to_char, the problem is solved!

Maybe you are looking for