Click here to Skip to main content
Click here to Skip to main content

Tutorial on Extended Stored Procedures for MS SQL Server v7.0

By , 9 Mar 2000
 
  • Download demo project - 296 Kb
  • Download source files - 11 Kb
  • Introduction

    Open Data Services is an interface that can be used to build robust applications that extend the power of MS SQL Server.

    Extended stored procedures

    An extended stored procedure is a C or C++ DLL that can be called from Transact-SQL using the same syntax as calling a Transact-SQL stored procedure. Extended stored procedures are a way to extend the capabilities of Transact-SQL to include any resources or services available to Microsoft Win32 applications.

    In other words you can create a Extended Stored Procedure in your custom language (VC++, VB, Delphi). These dll's can use API's provided by Open Data Services to interact, control and enhance the functionality of SQL server to provide the functionality you might require.

    Examples:

    1. Imagine you have an application that performs some processing on the basis of the some records inserted newly in a particular table. The common way that one may do the same is open a recordset connection on the table and keep polling and re-querying till a new entry is inserted.

      The drawback in the above example is polling, it would put a lot of burden on the table on frequently accessed tables. The Extended Stored Procedure would adopt an event based approach, where an extended stored procedure residing on the server would be triggered on a new insert and perform custom processing.

    2. Imagine you have an application that needs to perform some checks on some condition and immediately send a response mail to someone notifying of the event.

      The drawback in the above example is you might have a particular condition to trigger the event today and a totally different condition tomorrow. The Extended Stored Procedure would adopt an event-based approach where your custom dll could generate and manage mail, all that one would have to do is to trigger the Extended Stored Procedure in the SQL Server trigger.


    Some quick tips on installing an extended stored procedure.

    Adding an extended stored procedure:

    To add an extended stored procedure function in an extended stored procedure DLL, you must run the sp_addextendedproc system stored procedure, specifying the name of the function and the name of the DLL in which that function resides. The user executing the command has to be a SQL Server system administrator.

    For example, this command registers the function xp_sample, located in xp_sample.dll, as a SQL Server extended stored procedure:

    sp_addextendedproc 'xp_sample','xp_sample.dll'
    

    It is a good practice to place the extended stored procedure dll in the SQL Server bin path along with any dependent dlls. SQL Server uses the LoadLibrary() method to locate the dll.

    Removing an extended stored procedure:

    sp_dropextendedproc 'xp_sample','xp_sample.dll'
    

    How Extended Stored Procedures Work

    When a client call (from ISQL, your own application) to the extended stored procedure is performed which in turn executes an extended stored procedure, the request is transmitted to the SQL Server. SQL Server then locates the DLL associated with the extended stored procedure, and loads the DLL if it is not already loaded using the LoadLibrary() method. So inherently the first call to the stored procedure will have the overhead of loading the dll. Then SQL server calls the exported extended stored procedure located in the dll, which gets an interface to the SQL Server in form of a Server Procedure. Your procedure can then read parameters passed to it and return back results if it so intends.

    However if your extended stored procedure raises an exception its process is killed and you have to restart the SQL server. SQL server has to be restarted even if you intend to replace the XP dll as it may have been loaded.

    Programming

    The sample extended stored procedure provided xp_sample is compiled and tested in VC ver 6.0. It should work on version 5 too as it has been tested.

    I have created the sample by first creating a MFC Regular DLL statically linked. (VC 6 provides XP's in the AppWizard but when I started working on a project 6 months back we had to use VC Ver 5.0). Don’t forget to include the Srv.h which has the declarations of the ODS functions and link to the library opends60.lib.

    Then define your export Extended Stored Procedure function which is of the format:

    SRVRETCODE xp_sample(SRV_PROC *srvproc)
    

    Where srvproc is a handle to the client connection and SRVRETCODE indicates the success or failure code that you intend to return. Do not forget to include the function in the exports .DEF file. The sample first gets a count of the no of parameters passed to it using the srv_rpcparams function. Then it gets the length, type and data of each paramater using srv_paramlen, srv_paramtype, srv_paramdata functions respectively. It then appends all the data received and sends it back to the SQL Server using srv_describe, srv_sendrow and srv_senddone functions.

    Programming Conventions

    1. It is a recommended practice to name your extended stored procedure and your extended stored procedure dll to start with xp_ by convention.
    2. It is also recommended that all Microsoft SQL Server extended stored procedure DLLs implement and export the following function:<>

      __declspec(dllexport) ULONG __GetXpVersion()
      {
         return ODS_VERSION;
      }
      

      It helps to prevent warnings and allows version checks when your xp is installed against the ODS Library on the SQL Server Installed as your stored procedure library may require a ODS version higher than what is installed on the SQL Server on which it is intended to be installed.

    Debugging an Extended Stored Procedure

    To debug an extended stored procedure DLL by using Microsoft Visual C++ follow the following steps.

    1. Stop SQL Server.
    2. Copy the updated SQL server extended to SQL Server bin directory preferably.
    3. Register the SQL Server using the sp_addextendedproc system stored procedure.
    4. In the project settings output Debug category for:
      • Executable for debug session: Provide $MSSSQLSERVERPATH$\BINN\sqlservr.exe
      • Working Directory: Provide $MSSSQLSERVERPATH$\BINN
      • Program arguments: -c so that SQL server starts as an application and not as an service.
    5. You can then put your break points and debug as normal.

    Note:

    1. If you plan to use MFC in the stored procedure or any other dependencies be sure that it is statically linked or the dependency dlls are also available in the $MSSSQLSERVERPATH$\BINN path.
    2. Your include directory in options must contain the SQL Development tools include and lib paths.
    3. I have tried compiling and checking whether it works on SQL Server 6.5, it does. But I doubt Microsoft supports it for version 6.5.

    Best of luck and happy extended stored procedures.

    License

    This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

    About the Author

    Santosh Rao
    Architect
    India India
    Member
    1993 started with Computers
     
    BE(Computer Science) and MS (Software Systems)
     
    Industry Experience: 10 Years
     
    C, C++, VC++(MFC), .NET, C#, MTS, Queuing, ASP.NET, AJAX, Java, J2EE, SunOne, JMS
     
    Banking, Insurance & Pension,Health Care

    Sign Up to vote   Poor Excellent
    Add a reason or comment to your vote: x
    Votes of 3 or less require a comment

    Comments and Discussions

     
    You must Sign In to use this message board.
    Search this forum  
        Spacing  Noise  Layout  Per page   
    QuestionCall Java code from MS SQLmemberash200827 May '08 - 14:40 
    Hi,
     
    Is there a way to call Java code from MS SQL (stored procedure).
     
    Please let me know
     
    Ash2008
    GeneralhsussAnonymous6 May '05 - 18:54 
    Blush | :O
    GeneralSample app that calls this XPmemberTom Wright2 Feb '05 - 5:21 
    Do you or can you provide some app that calls this XP and returns what ever it is that you are returning?
     
    Thanks

     
    Tom Wright
    tawright915@yahoo.com
    GeneralLink to VOmemberthuehmer15 Dec '04 - 6:43 
    Can someone tell me how I can reference an active x dll, instantiate objects, and call methods and functions? Specifically I would simply want a VB dll with 1 function that accepts the array of parameters.
     
    Thanks in advance.
    GeneralRe: Link to VOmemberCristian Amarie27 Dec '04 - 4:12 
    Automation is available thru sp_OA... procedures family.
     
    sp_OACreate <--> CoCreateInstance(..., &pInterface);
    sp_OADestroy <--> pInterface->Release();
    sp_OAMethod <--> pInterface->Method(...);
     
    Check SQL Server Books Online for more details, searching for sp_OACreate etc.
     
    Note. sp_OA... family can be executed only by members of sysadmin.
    GeneralProblem in Stored ProcedurememberabhiVyas23 Aug '04 - 20:23 
    Hi,
    I have a database in sybase.
    I have some record like
    emp_no code date amt
    5001 1 12/03/04 200
    5001 3 12/03/04 200
    5001 2 12/03/04 200
    5002 1 12/03/04 250
    5002 3 12/03/04 100
     
    ok
    In this table code and amt is related
    code 1 for PF
    CODE 2 FOR CPF
    CODE 3 FOR VPF
    i want to display these records in
    following format
    emp_no date PF VPF CPF
    5001 12/03/04 200 200 200
    5002 12/03/04 250 100 0
     
    Table dont have any record as code 2 for emp_no=5002
    but i want to display 0 in report.
     
    Now i thing u have understand my problem.
     
    Plz help and reply
     
    Abhishek Vyas
    GeneralRe: Problem in Stored Procedurememberbaiju.km24 Aug '04 - 0:14 
    Hi,
    There's One Solution For U R Problem.Add Date Also.
     

    select emp_no ,
    PF = CASE WHEN SUM(t.PF) IS NULL THEN 0 ELSE SUM(t.PF) END,
    DF = CASE WHEN SUM(t.CPF) IS NULL THEN 0 ELSE SUM(t.CPF) END,
    SAL = CASE WHEN SUM(t.VPF) IS NULL THEN 0 ELSE SUM(t.VPF) END
    from
    (Select emp_no ,PF =
    case code
    when 1 Then amt
    End ,CPF =
    case code
    when 2 Then amt
    End ,VPF =
    case code when 3 Then amt
    Else '0'
    End
    from Employee )as t group by t.emp_no

     
    by
    baijumax Blush | :O

    GeneralFailed to compile xp_dblib.dllmemberMahabubur Rahaman21 Jul '04 - 17:40 
    Hi !!
    Good Morning!Smile | :) Smile | :)
    when ever i compile xp_dblib vc++ project which is included a extended stored procedure its display one error message like ODS_Version undefined declaration.
    Now how can I make the Dll?
    Plesae help me ?
     
    warmly
    Mahabubur Rahaman
    Bangladesh.

     
    NA
    GeneralSupport for 64-bitmemberxavitomorera3 May '04 - 12:13 
    Hi, what happens to support in 64-bit?
     
    I need to include Srv.H but I dont have the appropriate 64-bit libraries...
     
    Any help?

    QuestionHow can I put big image file to image fieldmembermarchday200421 Apr '04 - 21:13 
    I've ever thought to write a extended procedure to do so, and the book online for MSSQL Server suggested me use the function dbwritetext() of DB-Library for C.
    How can I call function dbwritetext() in my extended procedure? Must I get a login structure pointer first and then select a database to accomplish this call? It's so annoying to me.
    Wait online for help. Frown | :(

    General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

    Permalink | Advertise | Privacy | Mobile
    Web01 | 2.6.130523.1 | Last Updated 10 Mar 2000
    Article Copyright 2000 by Santosh Rao
    Everything else Copyright © CodeProject, 1999-2013
    Terms of Use
    Layout: fixed | fluid