T-SQL:从text或ntext列中选择前n个字符

时间:2009-08-02 16:55:56

标签: sql-server tsql

考虑一种情况,您希望从表中提取最后的x个条目。我们想要的列包含有关产品的推荐。出于性能原因,我们只想从推荐书中获取前50个字符。该列名为TestimonialText,类型为text

考虑这个简洁的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

这会产生错误:

  

参数数据类型文本无效   左功能的参数1。

问题:如何只提取text或ntext列的前几个 n 字符?

4 个答案:

答案 0 :(得分:11)

我认为SUBSTRING将是更好的选择。试试这个:

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

答案 1 :(得分:8)

如果您使用SQL Server 2005或更高版本,请不要使用text数据类型,因为它已被删除。使用varchar(max)或nvarchar(max)。所有字符串函数都可以。在此处阅读更多内容:http://msdn.microsoft.com/en-us/library/ms178158.aspx

答案 2 :(得分:6)

你正在寻找这样的东西吗?请注意SELECT语句中的 CAST(C.TestimonialText AS VARCHAR(50))

SELECT TOP 10
    C.FirstName + ' ' + C.LastName AS CustomerName,
    CAST(C.TestimonialText AS VARCHAR(50)) AS TestimonialSnippet,
    C.TestimonialDate
FROM Customer AS C  
ORDER BY C.TestimonialDate DESC

以下是一些测试数据

测试数据设置

create table #t (mytext text)
insert into #t VALUES ('1234567890')
insert into #t VALUES ('123')

SELECT
  mytext,
  CAST(mytext as varchar(5)) AS Snippet
FROM #t

结果

mytext     Snippet
---------- -------
1234567890 12345
123        123

答案 3 :(得分:1)

基本上发生的事情是你已经为LEFT函数的第一个参数提供了无效的数据类型。确保将文本数据类型转换为varchar或nvarchar,然后您的查询肯定有效。这是我在SQL Server 2005中测试的一个例子

Create table #Customer

(
 firstName varchar(30)
 ,lastName varchar(30)
 ,testimonial text
 ,testimonialDate DateTime

)

GO

INSERT INTO #Customer (firstName, lastName, testimonial, testimonialDate ) VALUES('Jonhn', 'Smith', 'we really really like your product and blaha ......', getDate())
GO
INSERT INTO #Customer (firstName, lastName, testimonial , testimonialDate) VALUES('Mary', 'Toe', 'we really really like your product and blaha ......', getDate() - 3)
GO
INSERT INTO #Customer (firstName, lastName, testimonial , testimonialDate) VALUES('Amanda', 'Palin', 'we really really like your product and blaha ......', getDate() -2 )
GO

SELECT TOP 3    C.FirstName + ' ' + C.LastName AS CustomerName    ,LEFT( CAST(C.Testimonial as varchar(50)),50) AS TestimonialSnippet    ,C.TestimonialDate FROM #Customer AS C  ORDER BY C.TestimonialDate DESC
GO
Drop table #Customer
GO