Link to home
Start Free TrialLog in
Avatar of Bruce Gust
Bruce GustFlag for United States of America

asked on

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?
Avatar of Big Monty
Big Monty
Flag of United States of America image

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
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

Avatar of Bruce Gust

ASKER

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?
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

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!
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?
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?
make sure your string of characters is longer than 78 chars, if it isn't, it won't truncate
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.
ASKER CERTIFIED SOLUTION
Avatar of Big Monty
Big Monty
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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.
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