如何在 SQL Server 中修剪字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/179625/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to trim a string in SQL Server?
提问by Eric Labashosky
In SQL Server 2017, you can use this syntax, but not in earlier versions:
在 SQL Server 2017 中,您可以使用此语法,但不能在早期版本中使用:
SELECT Name = TRIM(Name) FROM dbo.Customer;
回答by Ben Hoffstein
SELECT LTRIM(RTRIM(Names)) AS Names FROM Customer
回答by Kibbee
To Trim on the right, use:
要在右侧修剪,请使用:
SELECT RTRIM(Names) FROM Customer
To Trim on the left, use:
要修剪左侧,请使用:
SELECT LTRIM(Names) FROM Customer
To Trim on the both sides, use:
要修剪两侧,请使用:
SELECT LTRIM(RTRIM(Names)) FROM Customer
回答by onedaywhen
I assume this is a one-off data scrubbing exercise. Once done, ensure you add database constraints to prevent bad data in the future e.g.
我认为这是一次性的数据清理练习。完成后,确保添加数据库约束以防止将来出现错误数据,例如
ALTER TABLE Customer ADD
CONSTRAINT customer_names__whitespace
CHECK (
Names NOT LIKE ' %'
AND Names NOT LIKE '% '
AND Names NOT LIKE '% %'
);
Also consider disallowing other characters (tab, carriage return, line feed, etc) that may cause problems.
还要考虑禁止可能导致问题的其他字符(制表符、回车符、换行符等)。
It may also be a good time to split those Names into family_name
, first_name
, etc :)
这也可能是那些名字分成好时机family_name
,first_name
等:)
回答by razon
SELECT LTRIM(RTRIM(Replace(Replace(Replace(name,' ',' '),CHAR(13), ' '),char(10), ' ')))
from author
回答by rahularyansharma
in sql server 2008 r2 with ssis expression we have the trim function .
在带有 ssis 表达式的 sql server 2008 r2 中,我们有修剪功能。
SQL Server Integration Services (SSIS) is a component of the Microsoft SQL Server database software that can be used to perform a broad range of data migration tasks.
SQL Server 集成服务 (SSIS) 是 Microsoft SQL Server 数据库软件的一个组件,可用于执行广泛的数据迁移任务。
you can find the complete description on this link
您可以在此链接上找到完整的说明
http://msdn.microsoft.com/en-us/library/ms139947.aspx
http://msdn.microsoft.com/en-us/library/ms139947.aspx
but this function have some limitation in itself which are also mentioned by msdn on that page. but this is in sql server 2008 r2
但是此功能本身有一些限制,msdn 在该页面上也提到了这些限制。但这是在 sql server 2008 r2 中
TRIM(" New York ") .The return result is "New York".
回答by Kai-Ove B?hnisch
Extended version of "REPLACE":
“替换”的扩展版本:
REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(RTRIM(LTRIM(REPLACE("Put in your Field name", ' ',' '))),'''',''), CHAR(9), ''), CHAR(10), ''), CHAR(13), ''), CHAR(160), '') [CorrValue]