我在SQL Server中大字符串。 我想这个字符串截断为10或15个字符
原始字符串
this is test string. this is test string. this is test string. this is test string.
所需的字符串
this is test string. this is ......
我在SQL Server中大字符串。 我想这个字符串截断为10或15个字符
原始字符串
this is test string. this is test string. this is test string. this is test string.
所需的字符串
this is test string. this is ......
如果你只是想回到你的长字符串的几个字符,你可以使用:
select
left(col, 15) + '...' col
from yourtable
请参阅SQL拨弄演示 。
这将返回字符串的前15个字符,然后地连接了...
到它的结束。
如果你想确保不是字符串小于15没有得到...
那么你可以使用:
select
case
when len(col)>=15
then left(col, 15) + '...'
else col end col
from yourtable
请参阅SQL拨弄演示
您可以使用
LEFT(column, length)
要么
SUBSTRING(column, start index, length)
我认为答案这里是伟大的,但我想补充的情况。
有好几次我想取一定量的字符掉一个字符串的前面,而不必担心它的长度。 没有与RIGHT()和SUBSTRING()这样做的几种方法,但它们都需要知道的字符串,它有时可以慢下来的长度。
我一直使用的东西()函数:
SET @Result = STUFF(@Result, 1, @LengthToRemove, '')
这取代不必要的字符串的长度与一个空字符串。
你也可以使用CAST()操作:
Declare @name varchar(100);
set @name='....';
Select Cast(@name as varchar(10)) as new_name
你也可以使用下面的IIF避免case语句,只在需要时(仅在SQL Server 2012中良好及更高版本)增加了椭圆和case语句更符合ANSI标准(但更详细)
SELECT
col, LEN(col),
col2, LEN(col2),
col3, LEN(col3) FROM (
SELECT
col,
LEFT(x.col, 15) + (IIF(len(x.col) > 15, '...', '')) AS col2,
LEFT(x.col, 15) + (CASE WHEN len(x.col) > 15 THEN '...' ELSE '' END) AS col3
from (
select 'this is a long string. One that is longer than 15 characters' as col
UNION
SELECT 'short string' AS col
UNION
SELECT 'string==15 char' AS col
UNION
SELECT NULL AS col
UNION
SELECT '' AS col
) x
) y
CASE
WHEN col IS NULL
THEN ''
ELSE SUBSTRING(col,1,15)+ '...'
END AS Col