Reputation: 129
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
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
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