+ Reply to Thread
Page 1 of 2 1 2 LastLast
Results 1 to 10 of 12

Thread: Dynamic Stored Procedure without Building Strings

  1. #1
    The Barnfather jmurrayhead has much to be proud of jmurrayhead has much to be proud of jmurrayhead has much to be proud of jmurrayhead has much to be proud of jmurrayhead has much to be proud of jmurrayhead has much to be proud of jmurrayhead has much to be proud of jmurrayhead has much to be proud of jmurrayhead has much to be proud of jmurrayhead has much to be proud of jmurrayhead's Avatar
    Join Date
    Mar 2008
    Location
    Reston, VA
    Posts
    4,547
    Blog Entries
    9
    Real Name
    Jason
    Rep Power
    22

    Dynamic Stored Procedure without Building Strings

    Today, I just learned a neat trick that allows you to have a "dynamic" stored procedure without building a query string and executing it.

    For example, let's say we have the following table:

    candidateID int
    firstName varchar(25)
    lastName varchar(25)
    email varchar(100)
    isActive bit

    Typically, if I wanted to be able to search this table by any combination of candidate ID, First Name, Last Name or Email, I would have built a query like this:

    Code:
    CREATE PROC[dbo].[usp_SearchCandidates]
    @candidateID int,
    @firstName varchar(25),
    @lastName varchar(25),
    @email varchar(100)
     
    AS
     
    SET NO COUNT ON
     
    DECLARE @sql varchar(600)
     
    SELECT @sql = 'SELECT candidateID, firstName, lastName, email FROM candidates WHERE isActive = 1 '
     
    IF (@candidateID IS NOT NULL)
        BEGIN
            SELECT @sql = @sql + ' AND candidateID = ' + @candidateID + ' '
        END
     
    IF (@firstName IS NOT NULL)
        BEGIN
            SELECT @sql = @sql + ' AND firstName = ''' + REPLACE(@firstname,'''','''''') + ''' '
        END
    IF (@lastName IS NOT NULL)
        BEGIN
            SELECT @sql = @sql + ' AND lastName = ''' + REPLACE(@lastname,'''','''''') + ''' '
        END
     
    IF (@email IS NOT NULL)
        BEGIN
            SELECT @sql = @sql + ' AND email = ''' + REPLACE(@email,'''','''''') + ''' '
        END
     
    EXEC(@sql)
    
    However, today, my coworker showed me something that looks more clean and isn't "dynamically" built.

    Code:
    CREATE PROC [dbo].[usp_SearchCandidates]
    @candidateID int,
    @firstName varchar(25),
    @lastName varchar(25),
    @email varchar(100)
     
    AS
     
    SET NO COUNT ON
     
    SELECT
        [candidateID],
        [firstName],
        [lastName],
        [email]
    FROM
        [candidates]
    WHERE (isActive = 1 AND
    candidateID = ISNULL(@candidateID, candidateID) AND
    firstName = ISNULL(@firstName, firstName) AND
    lastName = ISNULL(@lastName, lastName) AND
    email = ISNULL(@email, email))
    
    For this to work, all parameters that aren't being utilized in the query should have a NULL value.
    jmurrayhead
    If you agree, give me rep.
    If you like it here...throw us a few bones to help support us.


  2. #2
    Barn Frequenter lewy is on a distinguished road lewy's Avatar
    Join Date
    Mar 2008
    Posts
    108
    Rep Power
    4

    Good example; however, if you look at it using Query Analyzer, this query is Very, Very expensive.
    Especially if you have a large database.
    A dynamic SQL statement is much more efficient.
    It even executes faster than a stored proc.

    This is one example in which a good old style SQL statement outguns its stored proc counterpart

  3. #3
    The Barnfather jmurrayhead has much to be proud of jmurrayhead has much to be proud of jmurrayhead has much to be proud of jmurrayhead has much to be proud of jmurrayhead has much to be proud of jmurrayhead has much to be proud of jmurrayhead has much to be proud of jmurrayhead has much to be proud of jmurrayhead has much to be proud of jmurrayhead has much to be proud of jmurrayhead's Avatar
    Join Date
    Mar 2008
    Location
    Reston, VA
    Posts
    4,547
    Blog Entries
    9
    Real Name
    Jason
    Rep Power
    22

    It took me 0:00:01 ms to run this query on a database with several thousand records. Maybe the database you tested it on isn't properly optimized
    jmurrayhead
    If you agree, give me rep.
    If you like it here...throw us a few bones to help support us.


  4. #4
    Barn Frequenter lewy is on a distinguished road lewy's Avatar
    Join Date
    Mar 2008
    Posts
    108
    Rep Power
    4

    I always look at a query using Query Analyzer and it's hardly wrong

    You are looking for exact information, how about when you're looking for matches using LIKE?

    btw - the new dbs I've been creating are very well optimized, though I can't say the same about the ones I inherited

  5. #5
    The Barnfather jmurrayhead has much to be proud of jmurrayhead has much to be proud of jmurrayhead has much to be proud of jmurrayhead has much to be proud of jmurrayhead has much to be proud of jmurrayhead has much to be proud of jmurrayhead has much to be proud of jmurrayhead has much to be proud of jmurrayhead has much to be proud of jmurrayhead has much to be proud of jmurrayhead's Avatar
    Join Date
    Mar 2008
    Location
    Reston, VA
    Posts
    4,547
    Blog Entries
    9
    Real Name
    Jason
    Rep Power
    22

    Quote Originally Posted by lewy View Post
    You are looking for exact information, how about when you're looking for matches using LIKE?
    That may be a different story. In many cases, it's not necessary to use LIKE. I guess I could have given a better example. I'm using a similar query where users select from several options like dates and specific values.

    Regardless, this is providing an alternative to using dynamically built queries.

    Quote Originally Posted by lewy View Post
    btw - the new dbs I've been creating are very well optimized, though I can't say the same about the ones I inherited
    Of course they are, lewy
    jmurrayhead
    If you agree, give me rep.
    If you like it here...throw us a few bones to help support us.


  6. #6
    Barn Frequenter lewy is on a distinguished road lewy's Avatar
    Join Date
    Mar 2008
    Posts
    108
    Rep Power
    4

    Good point

  7. #7
    I like Data Cubes too... Lauramc has a spectacular aura about Lauramc has a spectacular aura about Lauramc's Avatar
    Join Date
    Mar 2008
    Location
    Far Far Away
    Posts
    387
    Real Name
    Laura
    Rep Power
    5

    I have not checked the cost of a query utilizing this type of process, but I have grown fond of using CASE statements in a where clause in order to allow for different parameter values. It may be "expensive" to run, but it is easier to read, understand and maintain. Also.. I almost never get all the single quotes right on the first try
    "The Enrichment Center is required to remind you that first you will be baked, then there will be cake." - GLaDOS

  8. #8
    Administrator richyrich is a splendid one to behold richyrich is a splendid one to behold richyrich is a splendid one to behold richyrich is a splendid one to behold richyrich is a splendid one to behold richyrich is a splendid one to behold richyrich is a splendid one to behold richyrich's Avatar
    Join Date
    Mar 2008
    Location
    Somewhere only we know...
    Posts
    3,207
    Blog Entries
    14
    Real Name
    Rich
    Rep Power
    14

    I may have come up with a small problem with this.

    Where a field has a NULL value and you don't want to include it in the WHERE clause, ie you set the parameter for that field to NULL, it doesn't seem to return the records where the value of that field is NULL.

    I know some don't like to store NULL values in their DB, but I do, so is there a way round this?

    btw, I'm using MySQL, so don't know if this is just an issue with it rather than MSSQL.

  9. #9
    The Barnfather jmurrayhead has much to be proud of jmurrayhead has much to be proud of jmurrayhead has much to be proud of jmurrayhead has much to be proud of jmurrayhead has much to be proud of jmurrayhead has much to be proud of jmurrayhead has much to be proud of jmurrayhead has much to be proud of jmurrayhead has much to be proud of jmurrayhead has much to be proud of jmurrayhead's Avatar
    Join Date
    Mar 2008
    Location
    Reston, VA
    Posts
    4,547
    Blog Entries
    9
    Real Name
    Jason
    Rep Power
    22
    jmurrayhead
    If you agree, give me rep.
    If you like it here...throw us a few bones to help support us.


  10. #10
    Administrator richyrich is a splendid one to behold richyrich is a splendid one to behold richyrich is a splendid one to behold richyrich is a splendid one to behold richyrich is a splendid one to behold richyrich is a splendid one to behold richyrich is a splendid one to behold richyrich's Avatar
    Join Date
    Mar 2008
    Location
    Somewhere only we know...
    Posts
    3,207
    Blog Entries
    14
    Real Name
    Rich
    Rep Power
    14

    Quote Originally Posted by jmurrayhead View Post
    Yep, I got that. The SP executes without any errors, but if any of the fields you're not checking the value of are NULL, then it doesn't return the record.
    For example, if I had data like this
    Code:
    ID     forename      surname      email
    1        Richy            Rich      NULL
    2        Jason        Murrayhead    NULL
    
    And had this SP
    Code:
    CREATE PROCEDURE GetUser(ID INT, email VARCHAR (50))
    BEGIN
     
    SET @ID = ID;
    SET @email = email;
     
    SELECT * FROM tblUsers
    WHERE
    ID=IFNULL(@ID,users.ID) AND
    email=IFNULL(@email,users.email)
     
    END
    
    And I executed:
    Code:
    GetUser(NULL,NULL)
    
    No records get returned.
    Last edited by richyrich; March 17th, 2009 at 10:42 AM.

+ Reply to Thread
Page 1 of 2 1 2 LastLast

Similar Threads

  1. write a procedure.
    By guddu in forum Microsoft SQL Server
    Replies: 7
    Last Post: July 11th, 2008, 11:19 AM
  2. Using Parameterized Stored Procedure
    By richyrich in forum MySQL
    Replies: 14
    Last Post: June 12th, 2008, 08:00 AM
  3. Stored Procedures on MySQL
    By richyrich in forum MySQL
    Replies: 7
    Last Post: June 9th, 2008, 12:15 PM
  4. If statement stored procedure
    By peebman2000 in forum SQL Development
    Replies: 32
    Last Post: May 23rd, 2008, 04:54 PM
  5. Dynamic Stored Procedure
    By jmurrayhead in forum Microsoft SQL Server
    Replies: 16
    Last Post: March 26th, 2008, 12:19 PM

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

SEO by vBSEO