views:

225

answers:

4

I need to trim a field in SQL Server table, when i use a select statement.

The requirement is that this field populates the dropdownlist in .net page. The maximum length that the data needs to display is 20. If data length is more than that, then it should be cut to 20, if less then the data length should be the length of string.

How do i do this?

+2  A: 

Try left(sting_field,20) or right(sting_filed,20)

adopilot
with this if the string length is say 10, will the new string be only 10 or 10 + 10 spaces?
reefes
String will remain 10
adopilot
+3  A: 

This SELECT should do:

SELECT 
  SUBSTRING(ISNULL(stringfield, ''), 1, 20)

It will replace a "NULL" value with an empty string '' and limit length to 20 chars max.

marc_s
Isn't LEFT() better than SUBSTRING()?
RickNZ
@RickNZ: why? how?
marc_s
+1  A: 

You can use the LEFT command.

TLiebe
A: 

I am confused... why dont you have the code that populates the dropdown manage the length of the data being loaded.

If you must do it within a query you could simply do a substring on the column:

http://msdn.microsoft.com/en-us/library/ms187748.aspx

Courtland