text and ntext are difficult to work with because many of the available string handling functions don't work with that data type. If you are using SQL Server 2005, then I recommend you change the data type to nvarchar(max). There is a way to make the query work while not having to worry about the length of the string contained within the ntext column.
If this column was a varchar(100), and you wanted to get the last 5 characters, the answer would be simple.
[tt][blue]Select Right(Column, 5)
From TableName[/blue][/tt]
Unfortunately, this code will NOT work for a TEXT or NTEXT column. Why? Because the Right function does not support that data type. You would get this error.
[tt][!]Server: Msg 8116, Level 16, State 2, Line 11[/!]
Argument data type ntext is invalid for argument 1 of len function.[/tt]
Fortunately, there is a SubString function that you can use. Unfortunately, you need to provide the starting position in order to use it effectively. Again... if you had a varchar column, you could use this.
[tt][blue]Select SubString(Column, Len(Column)-5, 5)[/blue][/tt]
Unfortunately, this doesn't work either because you cannot supply a text or ntext column to the LEN function.
So, as you can see, there are a lot of problems with using Text or nText data types. If you can change the column to another data type, then I would recommend you do so. There is, of course, another way to accommodate this query.
SQL Server has a DataLength function that you can use. In this situation, you need to understand the difference between Len and DataLength. Len will return the number of characters that are contained within a 'string' variable. DataLength will return the number of BYTES required to store the data. There is a subtle, yet important distinction. The difference between text and [!]n[/!]text is that ntext can accommodate unicode characters. unicode requires 2 bytes per character to store, so DataLength will return double the number of characters because it takes 2 bytes to store each one.
To see what I mean, copy/paste this to query analyzer.
Code:
Declare @temp nvarchar(20)
Set @Temp = 'Hello'
Select Len(@Temp), DataLength(@Temp)
When you run that code, you will get:
[tt][blue]Len_Output DataLength_Output
----------- -----------------
5 10
(1 row(s) affected)[/blue][/tt]
I mentioned SubString earlier in this post. SubString does work with ntext, so we can use that function. The second parameter to the SubString function specifies the starting position (in characters). So, we will need to calculate that. DataLength can be used for this, but remember that it returns the number of bytes, so we will need to divide by 2.
Finally, to get the last 5 digits of an ntext column, you can use this...
Code:
Select SubString(ColumnName, DataLength(ColumnName)/2 - 4, 5)
From TableName
Make sense?
-George
"The great things about standards is that there are so many to choose from." - Fortune Cookie Wisdom