reefes
reefes

Reputation: 129

Return first N characters of string

I need to select a shortened version of a field from a SQL Server table to use in a drop down list.

This field has to be limited to twenty characters. If the field has more than twenty characters, it should display the first twenty; if it has less than twenty characters, it should display the whole string.

How do I do this?

Upvotes: 12

Views: 45778

Answers (4)

Courtland
Courtland

Reputation: 56

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:

https://learn.microsoft.com/en-us/sql/t-sql/functions/substring-transact-sql

Upvotes: 0

adopilot
adopilot

Reputation: 4500

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

Upvotes: 22

TLiebe
TLiebe

Reputation: 7976

You can use the LEFT command.

Upvotes: 3

marc_s
marc_s

Reputation: 754408

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.

Upvotes: 4

Related Questions