2009-08-02 18 views
6

Considere un escenario en el que le gustaría extraer las últimas x entradas de una tabla. La columna que queremos contiene testimonios sobre un producto. Por motivos de rendimiento, solo queremos obtener los primeros 50 caracteres del testimonio. La columna se llama TestimonialText y es del tipo text.T-SQL: seleccionar los primeros n caracteres de una columna de texto o texto

Considérese este fragmento condensada de 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 

Esto produce un error:

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

Pregunta: cómo extraer únicamente las primeras n caracteres del texto o ntext ¿columna?

Respuesta

10

creo SUBSTRIN G sería una mejor opción. Prueba esto:

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

Gracias Bird. 'SUBSTRING' es el camino a seguir si no quieres lanzar a' varchar'. –

8

Si usa SQL Server 2005 o superior, no use el tipo de datos de texto, porque está privado. Use varchar (max) o nvarchar (max). Todas las funciones de cadena funcionarán. Lea más aquí: http://msdn.microsoft.com/en-us/library/ms178158.aspx

+0

Gracias Sergey, agradezco la nota sobre el tipo de datos privado. –

6

¿Está buscando algo como esto? Tenga en cuenta que CAST (C.TestimonialText AS VARCHAR (50)) en la instrucción SELECT.

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 

Aquí es algunos datos de prueba

configuración de datos de prueba

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 

Resultados

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

Básicamente lo que tiene esto pasó es que nos ha proporcionado el tipo de datos no válido para el primer parámetro de la función IZQUIERDA. Asegúrese de convertir el tipo de datos de texto como varchar o nvarchar, entonces su consulta definitivamente funciona. Aquí hay un ejemplo que probé en 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 
Cuestiones relacionadas