Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T-SQL: Selecting top n characters from a text or ntext column

Consider a scenario where you'd like to pull the last x entries from a table. The column we want contains testimonials about a product. For performance reasons, we only want to grab the first 50 characters from the testimonial. The column is named TestimonialText and is of type text.

Consider this condensed snippet of T-SQL:

SELECT TOP 10
    C.FirstName + ' ' + C.LastName AS CustomerName
    ,LEFT(C.TestimonialText,50) AS TestimonialSnippet
    ,C.TestimonialDate

FROM Customer AS C  
ORDER BY C.TestimonialDate DESC

This produces an error:

Argument data type text is invalid for argument 1 of left function.

Question: how to extract just the first few n characters of the text or ntext column?

like image 382
p.campbell Avatar asked Aug 02 '09 16:08

p.campbell


People also ask

How can you capture the length of a column when it is a text Ntext and or image data type?

Solution. In addition to the LEN() function, SQL Server also has a DATALENGTH() function. This function can be used on all data types in your table. That's all there is to it.

How do I select the first 4 characters in SQL?

SQL Server LEFT() Function The LEFT() function extracts a number of characters from a string (starting from left).


2 Answers

I think SUBSTRING would be a better choice. Try this:

SELECT TOP 10
    C.FirstName + ' ' + C.LastName AS CustomerName
    ,SUBSTRING(C.TestimonialText,1,50) AS TestimonialSnippet
    ,C.TestimonialDate
FROM Customer AS C  
ORDER BY SUBSTRING(C.TestimonialText,1,50) DESC
like image 136
northpole Avatar answered Oct 15 '22 11:10

northpole


If you use SQL Server 2005 or above, do not use text datatype, because it's depricated. Use varchar(max) or nvarchar(max). All string functions will work. Read more here: http://msdn.microsoft.com/en-us/library/ms178158.aspx

like image 33
Sergey Olontsev Avatar answered Oct 15 '22 12:10

Sergey Olontsev