I am creating T-SQL SELECT statements for tables for which I do not have data type information up. In these instructions, I need to perform row manipulation operations, which depend on the length of the original value of the table columns.
One example (but not the only one) is to insert some text at a specific position in a line, including the ability to insert it at the end:
SELECT
CASE WHEN (LEN ([t0].[Product] = 8)
THEN [t0].[Product] + 'test'
ELSE STUFF ([t0].[Product], 8, 0, 'test')
END
FROM [OrderItem] [t0]
(CASE WHEN + LEN is required because STUFF does not allow me to insert text at the end of a line.)
The problem is that LEN eliminates trailing spaces that will ruin the computation. I know that I can use DATALENGTH, which does not exclude trailing spaces, but I cannot convert the bytes returned by DATALENGTH to the characters required by STUFF, because I don't know if the Product column is of type varchar or nvarchar.
So, how can I generate an SQL statement that depends on the exact length of the string in characters without prior information about the string data type used?
source
share