tags:

views:

59

answers:

4

I'm wondering if there is a way I can pass in a string (varchar) to a (custom) function in MySQL and then have it output the string ordered alphabetically. I am unsure of how you would actually reorder the string.

IN : dbca
OUT: abcd
+2  A: 

I'd be surprised if there was a such function. Never mind, you can implement your own functions.

Zed
+2  A: 

You won't be able to do that directly through SQL; you'll have to do a SELECT and UPDATE from a programming language.

VoteyDisciple
+2  A: 

One could probably define a stored function that could do this, but it would be pretty awkward and inefficient. This doesn't taking advantage of the strengths of SQL.

However, it would be simple in many dynamic programming languages:

<?php
$in = "dbca";
$out = str_split($in);
sort($out);
print_r($out);
Bill Karwin
A: 

I decided to take Bill's example and this is what I came up with:

function orderAlpha($letters)
{
    $mySortedArray = str_split($letters);
    sort($mySortedArray);

    return implode($mySortedArray);
}


loop until all records are updated:

$stmt = new PDOStatement(); 
$stmt = $dbh->prepare("SELECT word FROM words WHERE ordered IS NULL LIMIT 1");
$stmt->execute();

if ($stmt->rowCount() > 0) {
    $result = $stmt->fetchAll();
    $word = $result[0]['word'];
    $orderedWord = orderAlpha($word);
    $stmt2 = new PDOStatement();
    $stmt2 = $dbh->prepare("UPDATE words SET ordered = :orderedWord WHERE word = :word");

    $stmt2->bindParam(':orderedWord', $orderedWord, PDO::PARAM_STR);
    $stmt2->bindParam(':word', $word, PDO::PARAM_STR);
    $stmt2->execute();
}
Joe Philllips
Cool! FYI, you don't need `$stmt = new PDOStatement;` because `prepare()` creates a statement.
Bill Karwin
I think I do that because there used to be a bug in PHP if you didn't do that. It's probably fixed by now. Thanks though.
Joe Philllips