Go Back   SitePoint Forums > Forum Index > Program Your Site > Databases > MySQL
Newsletter FAQ Members List Calendar Mark Forums Read

New to SitePoint Forums? Register here for free!

SitePoint Sponsor
 
 
 
Thread Tools Display Modes
Prev Previous Post   Next Post Next
Old Nov 12, 2009, 07:21   #1
djeyewater
SitePoint Member
 
Join Date: Dec 2008
Posts: 19
How to set a variable if a row already exists?

I have a table like so:
SQL Code:
CREATE TABLE `shortURL` (
 `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
 `sURL` varchar(5) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
 `lURL` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 PRIMARY KEY (`id`),
 UNIQUE KEY `lURL` (`lURL`),
 KEY `sURL` (`sURL`)
) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
What I want to do is to try inserting a new row with a value into the lURL field, but if the record already exists, then set a variable @sURL to the value of the sURL column for the record in question.

Currently I'm doing this like so:
MySQL Code:
INSERT INTO shortURL VALUES(NULL, '', lURL)
        #If the long URL already exists, then set @sURL to the short URL value
        ON DUPLICATE KEY UPDATE
        id = IF( (@sURL := sURL), id, id);

Is there a better way of setting the @sURL to the value of sURL if the record already exists?

The full procedure looks like this:
SQL Code:
CREATE FUNCTION makesURL (lURL CHAR(255))
RETURNS CHAR(5) DETERMINISTIC
BEGIN
    #First try and insert the long URL
    INSERT INTO shortURL VALUES(NULL, '', lURL)
        #If the long URL already exists, then set @sURL to the short URL value
        ON DUPLICATE KEY UPDATE
        id = IF( (@sURL := sURL), id, id);
    #If the record didn't already exist, so we've just inserted a new record, create the short URL and update the record
    IF @sURL IS NULL THEN
        SET @sURL = strFromNum(LAST_INSERT_ID());
        UPDATE shortURL SET shortURL.sURL = @sURL
            WHERE shortURL.id = LAST_INSERT_ID()
            LIMIT 1;
    END IF;
    RETURN @sURL;
END//

P.S. Most records will be new, so trying to insert the record first rather than trying to select it first is much faster.

Thanks

Dave
djeyewater is offline   Reply With Quote
 

Bookmarks

« Previous Thread | Next Thread »

Thread Tools
Display Modes

 
Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Sponsored Links
 
Forum Jump


All times are GMT -7. The time now is 00:55.


Powered by vBulletin® Version 3.7.1
Copyright ©2000 - 2010, Jelsoft Enterprises Ltd.
Copyright 1998-2009, SitePoint Pty Ltd. All Rights Reserved