truncating a field value in a SQL select

Go To StackoverFlow.com

1

In a SQL statement, how do you limit the returned value of a text field char length to a certain size?

Tried so far-

select len(mytextfield,30) from table
2012-04-05 02:09
by Average Joe
SubString : http://msdn.microsoft.com/en-us/library/ms187748%28v=sql.105%29.asp - shenhengbin 2012-04-05 02:12


4

You want the SUBSTRING function.

SELECT SUBSTRING(mytextfield, 1, 30) FROM Table

(This is assuming SQL Sever / T-SQL; you didn't specify a database engine.)

2012-04-05 02:11
by Jeremy Wiggins
@ downvoter - care to explain why - Jeremy Wiggins 2012-04-05 02:18
don't know why I got a -2 down vote. Not that i care but just weird. but anyway, it's mysql. I'm sorry for not including it in the original question. Now I tagged the q with mysql - Average Joe 2012-04-05 04:00
@AverageJoe - SUBSTRING and LEFT should work with mySql as well - Jeremy Wiggins 2012-04-05 10:30


1

select left(mytextfield,30)

I am not positive, but I think the substring function does not work against the TEXT datatype.

2012-04-05 02:18
by datagod
+1 from me - but from MSDN's SUBSTRING documentation - "Returns part of a character, binary, text, or image expression. - Jeremy Wiggins 2012-04-05 02:21
I can't recall right now what the problem was, it might be a SQL 2000 thing. There are definitely things you can't do with TEXT, one of the reasons that VARCHAR(max) comes in handy - datagod 2012-04-05 03:36
Ads