Question

I have a text column that I want to see if it has larger than 4000 characters. If it does have more than 4000 characters, then start at the right most character and go back 4000 characters.

I realize that the following code is not correct. But it is a start.

select 
case 
when datalength(column1) > 4000 then
right(column1, 4000)
case datalength(column1) <= 4000 then 
column1
end 
from table_1
Était-ce utile?

La solution

In SQL Server:

SELECT CASE
    WHEN (DATALENGTH(column1) > 4000)
    THEN SUBSTRING(column1, DATALENGTH(test) - 3999, DATALENGTH(column1))
    ELSE column1
END
FROM table_1

Not fantastic, since you're recalculating DATALENGTH(column1) three times.

EDIT

Calculating only once using a CTE:

WITH CTE AS
(
    SELECT DATALENGTH(column1) AS LENGTH, column1 FROM table_1
)
SELECT CASE
    WHEN (LENGTH > 4000)
    THEN SUBSTRING(column1, LENGTH - 3999, LENGTH)
    ELSE column1
END
FROM CTE

Autres conseils

This works in Oracle. Here is the documentation on Substr: http://psoug.org/definition/SUBSTR.htm

select (case when length(column1) > 4000 
             then substr(column1, -4000) 
             else column1 
        end) 
from table_1;

In SQL Server

SELECT
  CASE WHEN datalength(MyColumn) > 4000 THEN SUBSTRING(REVERSE(MyColumn), 1, 4000) ELSE MyColumn END AS MyGenCol
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top