Can I select only a portion of the text in a column within a stored procedure?

Here's what I want to do:

I've got a recordset that I'm calling using a stored procedure. Rather than the entire "description" field, I want to be able to limit what's there to 75 characters and follow the last word with a "...".

I've done this before using something like this:

$position = '150';                    
        $message = $description;                    
        $post = substr($message,$position,1);                                        
        if($post !=" ") {                    
        $length = strlen( $message );                    
        while($post !=" " && $position < $length){                    
        $i =1;                    
        $position = $position+$i;                    
        $message =$description;                    
        $post = substr($message,$position,1);  

But I want to try to do the heavy lifting within the store procedure. Is that possible and, if so, how?

This is what my stored procedure looks like currently:

SELECT  at.shortname as assetshortname, en.shortname as entityshortname, st.shortname as statusshortname, cer.cermodelid, cer.assettypeid, 
cer.statusid, cer.createuserid, cer.entityid, cer.createdate, cer.description 
from cer_Model cer 
inner join fin_AssetType at on at.assettypeid = cer.assettypeid
inner join ptl_Entity en on en.entityid = cer.entityid
inner join ptl_Status st on st.statusid = cer.statusid
where cer.createuserid = @UserID 
order by cer.createdate

Open in new window


What do you think?
brucegustPHP DeveloperAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Big MontyWeb Ninja at largeCommented:
You could probably do something like this:

in your select clause, for the description field, change it to:

description = case Len( cer.description ) when 78 then Left( cer.description, 75 ) + '...' else cer.description end
0
Ray PaseurCommented:
In publishing this is called a "teaser fragment" and it's done this way in PHP.  I've never tried to do it in SQL.

<?php // demo/teaser_fragment.php
error_reporting(E_ALL);


// CREATE A TEASER FRAGMENT HEADLINE
// RETURN FIRST FEW WHOLE WORDS FOLLOWED BY ELLIPSES
// WITH A LINK TO THE FULL ARTICLE
// $length IS MINIMUM TRUNCATION CHARACTER COUNT


function teaser_fragment($text, $length=32, $url='#', $delim='|||')
{
    // IF TRUNCATION IS NEEDED
    if (strlen($text) > $length)
    {
        // IF TRUNCATION IS NEEDED, BREAK STRING APART
        $t = wordwrap($text, $length, $delim);
        $a = explode($delim, $t);
        $z = '...';
    }
    // IF TRUNCATION IS NOT NEEDED
    else
    {
        $a[0] = $text;
        $z = NULL;
    }

    // CONSTRUCT THE FRAGMENT WITH THE LINK AND ADD ELLIPSIS (LINK) TO THE END
    $teaser
    = '<a target="_blank" href="'
    . $url
    . '">'
    . $a[0]
    . $z
    . '</a>'
    ;
    return $teaser;
}



// USE CASES
echo "<pre>";
echo PHP_EOL;
echo "1...5...10...15...20...25...30...35...40...45..." . PHP_EOL;
echo teaser_fragment('Now is the time for all good men to come to the aid of their party');

echo PHP_EOL;
echo teaser_fragment('Now is the time for all good men to come to the aid of their party', 300);

echo PHP_EOL;
echo teaser_fragment('Now is the time for all good men to come to the aid of their party', 15, 'http://en.wikipedia.org/wiki/Filler_text');

Open in new window

0
brucegustPHP DeveloperAuthor Commented:
Big Monty, this looks great, but would you be willing to show me how your suggestion gets inserted into my current procedure?

Here's the entire code:

USE [BIProd]
GO
/****** Object:  StoredProcedure [dbo].[cer_ModelList]    Script Date: 3/4/2014 10:50:02 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[cer_ModelList]
    @UserID int
AS
SET NOCOUNT ON;

SELECT  at.shortname as assetshortname, en.shortname as entityshortname, st.shortname as statusshortname, cer.cermodelid, cer.assettypeid, 
cer.statusid, cer.createuserid, cer.entityid, cer.createdate, cer.description 
from cer_Model cer 
inner join fin_AssetType at on at.assettypeid = cer.assettypeid
inner join ptl_Entity en on en.entityid = cer.entityid
inner join ptl_Status st on st.statusid = cer.statusid
where cer.createuserid = @UserID 
order by cer.createdate

Open in new window


How do I incorporate your syntax?
0
10 Tips to Protect Your Business from Ransomware

Did you know that ransomware is the most widespread, destructive malware in the world today? It accounts for 39% of all security breaches, with ransomware gangsters projected to make $11.5B in profits from online extortion by 2019.

Big MontyWeb Ninja at largeCommented:
change your select statement to:

SELECT  at.shortname as assetshortname, en.shortname as entityshortname, st.shortname as statusshortname, cer.cermodelid, cer.assettypeid, 
cer.statusid, cer.createuserid, cer.entityid, cer.createdate, 
description = case Len( cer.description ) when 78 then Left( cer.description, 75 ) + '...' else cer.description end
from cer_Model cer 
inner join fin_AssetType at on at.assettypeid = cer.assettypeid
inner join ptl_Entity en on en.entityid = cer.entityid
inner join ptl_Status st on st.statusid = cer.statusid
where cer.createuserid = @UserID 
order by cer.createdate

Open in new window

0
brucegustPHP DeveloperAuthor Commented:
Sweet! One more thing...

In my HTML, I'm echoing your "description" like this: .$modellist[$i]["description"] with that query looking like...

if (!function_exists('cer_modellist')) {
    function cer_modellist($userid) {
        global $edb,$_SESSION;
        
        $data = array();
         $sql_data = "exec cer_ModelList $userid";
         if ($_SESSION["portaladmin"] == 1 && $_SESSION["showsql"] != "no")
            echo display_detail("cer_functions.php",$sql_data);
        $result_data = odbc_exec($edb, $sql_data);
        
        $count = 0;
        while (odbc_fetch_row($result_data))
            {
            $count++;
            $data[$count]["cermodelid"]= odbc_result($result_data, "cermodelid");
            $data[$count]["createuserid"] = odbc_result($result_data, "createuserid");
            $data[$count]["assetshortname"] = htmlspecialchars(odbc_result($result_data, "assetshortname"), ENT_QUOTES);
            $data[$count]["statusid"] = htmlspecialchars(odbc_result($result_data, "statusid"), ENT_QUOTES);
            $data[$count]["entityshortname"] = htmlspecialchars(odbc_result($result_data, "entityshortname"), ENT_QUOTES);
            $data[$count]["description"] = htmlspecialchars(odbc_result($result_data, "description"), ENT_QUOTES);
            $data[$count]["statusshortname"] = htmlspecialchars(odbc_result($result_data, "statusshortname"), ENT_QUOTES);
            $data[$count]["createdate"] = date('m/d/Y', strtotime(odbc_result($result_data, "createdate")));
            }
        $data["count"] = $count;
        return $data;
        }
    }

Open in new window


I'm still getting the entire text. What do I need to change in order to get your new and improved version. And I have successfully changed and saved your new stored procedure!
0
Big MontyWeb Ninja at largeCommented:
I'm not much of a PHP guy, so I can't really help you there...

Did you try running the SP directly in the database to see if the results are correct?
0
brucegustPHP DeveloperAuthor Commented:
Well, now that you mention it, while there were no errors, when I ran the query in the Management Studio, while I didn't get any errors, I didn't get an abbreviated description. What do I need to change?
0
Big MontyWeb Ninja at largeCommented:
make sure your string of characters is longer than 78 chars, if it isn't, it won't truncate
0
brucegustPHP DeveloperAuthor Commented:
I've got one description which is "I changed the varchar for this field to 500 rather than 250. Gives the user the chance to elaborate a bit more."

Just some nonsense to fill some space.

Then I went back into your query and changed 78 to 10 just so the exaggerated value might make it more obvious as to whether or not things were working right.

When I hit "Execute Query" I get the entire description field in every row.
0
Big MontyWeb Ninja at largeCommented:
sorry, i goofed, i had it EQUAL to 78, when it should be greater than:

SELECT  at.shortname as assetshortname, en.shortname as entityshortname, st.shortname as statusshortname, cer.cermodelid, cer.assettypeid, 
cer.statusid, cer.createuserid, cer.entityid, cer.createdate, 
description = case when Len( cer.description ) >= 78 then Left( cer.description, 75 ) + '...' else cer.description end
from cer_Model cer 
inner join fin_AssetType at on at.assettypeid = cer.assettypeid
inner join ptl_Entity en on en.entityid = cer.entityid
inner join ptl_Status st on st.statusid = cer.statusid
where cer.createuserid = @UserID 
order by cer.createdate

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
brucegustPHP DeveloperAuthor Commented:
That did it and it's showing up great!

One last thing, and I'm going to go ahead and award you your points so I'm not trying to get more than my money's worth...

Is there a way to prevent words from being truncated? So instead of buil..., it would say building...

Let me know if you want me to open up another question, but I would be interested in knowing if there's a way to do it.
0
Big MontyWeb Ninja at largeCommented:
i'm sure there is a way to do it, you would have to search for a white space around the 75 char mark. I'm not sure what the syntax would be, but i'm sure someone else could assist you
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.