Solved

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

Posted on 2014-03-04
12
177 Views
Last Modified: 2014-03-04
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?
0
Comment
Question by:brucegust
  • 6
  • 5
12 Comments
 
LVL 32

Expert Comment

by:Big Monty
ID: 39903814
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
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 39903881
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
 

Author Comment

by:brucegust
ID: 39903883
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
 
LVL 32

Expert Comment

by:Big Monty
ID: 39903891
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
 

Author Comment

by:brucegust
ID: 39903914
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
 
LVL 32

Expert Comment

by:Big Monty
ID: 39903932
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
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 

Author Comment

by:brucegust
ID: 39903969
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
 
LVL 32

Expert Comment

by:Big Monty
ID: 39903977
make sure your string of characters is longer than 78 chars, if it isn't, it won't truncate
0
 

Author Comment

by:brucegust
ID: 39904034
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
 
LVL 32

Accepted Solution

by:
Big Monty earned 500 total points
ID: 39904048
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
 

Author Comment

by:brucegust
ID: 39904057
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
 
LVL 32

Expert Comment

by:Big Monty
ID: 39904067
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

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

This article explains how to reset the password of the sa account on a Microsoft SQL Server.  The steps in this article work in SQL 2005, 2008, 2008 R2, 2012, 2014 and 2016.
This article discusses four methods for overlaying images in a container on a web page
Via a live example, show how to shrink a transaction log file down to a reasonable size.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now