如何从 SQL Server 中的列中删除字符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/983417/
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 do you strip a character out of a column in SQL Server?
提问by Even Mien
How do you remove a value out of a string in SQL Server?
如何从 SQL Server 中的字符串中删除值?
回答by Jose Basilio
This is done using the REPLACEfunction
这是使用REPLACE函数完成的
To strip out "somestring" from "SomeColumn" in "SomeTable" in the SELECT query:
要从 SELECT 查询的“SomeTable”中的“SomeColumn”中去除“somestring”:
SELECT REPLACE([SomeColumn],'somestring','') AS [SomeColumn] FROM [SomeTable]
To update the table and strip out "somestring" from "SomeColumn" in "SomeTable"
更新表格并从“SomeTable”中的“SomeColumn”中去除“somestring”
UPDATE [SomeTable] SET [SomeColumn] = REPLACE([SomeColumn], 'somestring', '')
回答by marc_s
Use the "REPLACE" string function on the column in question:
在相关列上使用“REPLACE”字符串函数:
UPDATE (yourTable)
SET YourColumn = REPLACE(YourColumn, '*', '')
WHERE (your conditions)
Replace the "*" with the character you want to strip out and specify your WHERE clause to match the rows you want to apply the update to.
将“*”替换为要删除的字符,并指定 WHERE 子句以匹配要应用更新的行。
Of course, the REPLACE function can also be used - as other answerer have shown - in a SELECT statement - from your question, I assumed you were trying to update a table.
当然,也可以使用 REPLACE 函数 - 正如其他回答者所显示的 - 在 SELECT 语句中 - 从您的问题中,我假设您正在尝试更新表。
Marc
马克
回答by RSolberg
Take a look at the following function - REPLACE():
看看下面的函数 - REPLACE():
select replace(DataColumn, StringToReplace, NewStringValue)
//example to replace the s in test with the number 1
select replace('test', 's', '1')
//yields te1t
http://msdn.microsoft.com/en-us/library/ms186862.aspx
http://msdn.microsoft.com/en-us/library/ms186862.aspx
EDIT
If you want to remove a string, simple use the replace function with an empty string as the third parameter like:
编辑
如果要删除字符串,只需使用带有空字符串的替换函数作为第三个参数,例如:
select replace(DataColumn, 'StringToRemove', '')
回答by TheTXI
UPDATE [TableName]
SET [ColumnName] = Replace([ColumnName], '[StringToRemove]', '[Replacement]')
In your instance it would be
在你的例子中,它将是
UPDATE [TableName]
SET [ColumnName] = Replace([ColumnName], '[StringToRemove]', '')
Because there is no replacement (you want to get rid of it).
因为没有替代品(你想摆脱它)。
This will run on every row of the specified table. No need for a WHERE clause unless you want to specify only certain rows.
这将在指定表的每一行上运行。除非您只想指定某些行,否则不需要 WHERE 子句。