我有一个带有几个固定长度字符字段的关系数据库。我需要使用-
等其他字符永久替换所有嵌入空格,以便JOHN DOE
成为JOHN-DOE
,ITSY BISTSY SPIDER
成为ITSY-BISTSY-SPIDER
。我可以事先搜索,以确保没有可能发生冲突的字符串。我只需要能够打印没有嵌入空格的请求文件。我会在C代码中进行替换,但我想确保数据库中存在JANE DOE
和JANE-DOE
的未来情况。
顺便说一句,我已经确定没有多个连续嵌入空间的字符串或前导空格只有尾随空格来填充固定长度字段。
编辑:感谢所有帮助!
看起来像我切割时将我的问题从Word粘贴到StackOverflow,尾随空格丢失了,所以我的问题的含义有点丢失。
我只需要替换嵌入的空格而不是尾随空格!
注意:我使用中间点代替不能很好显示的空格。
使用:
SELECT REPLACE(operator_name, ' ', '-') FROM operator_info ;
字符串JOHN·DOE············
变为JOHN-DOE------------
。
我需要JOHN-DOE············
。
我在想我需要使用别名和TRIM
命令但不确定如何。
答案 0 :(得分:7)
在您的特定数据库中内置任何REPLACE功能。
MySQL的: http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_replace
甲骨文: http://psoug.org/reference/translate_replace.html
SQLServer的: http://msdn.microsoft.com/en-us/library/ms186862.aspx
根据您的评论编辑以下内容。
我已经在SQLServer语法中完成了这个,所以请根据需要修改示例。第一个例子真正打破了正在发生的事情,第二个例子将它全部集成到一个丑陋的查询中:D
在这种情况下,@output 包含您的最终价值。
DECLARE @input VARCHAR (100) = ' some test ';
DECLARE @trimmed VARCHAR (100);
DECLARE @replaced VARCHAR (100);
DECLARE @output VARCHAR (100);
-- Get just the inner text without the preceding / trailing spaces.
SET @trimmed = LTRIM (RTRIM (@input));
-- Replace the spaces *inside* the trimmed text with a dash.
SET @replaced = REPLACE (@trimmed, ' ', '-');
-- Take the original text and replace the trimmed version (with the inner spaces) with the dash version.
SET @output = REPLACE (@input, @trimmed, @replaced);
-- Show each step of the process!
SELECT @input AS INPUT,
@trimmed AS TRIMMED,
@replaced AS REPLACED,
@output AS OUTPUT;
作为SELECT语句。
DECLARE @inputTable TABLE (Value VARCHAR (100) NOT NULL);
INSERT INTO @inputTable (Value)
VALUES (' some test '),
(' another test ');
SELECT REPLACE (Value,
LTRIM (RTRIM (Value)),
REPLACE (LTRIM (RTRIM (Value)), ' ', '-'))
FROM @inputTable;
答案 1 :(得分:2)
如果您使用的是MSSQL:
SELECT REPLACE(field_name,' ','-');
编辑:在跳过尾随空格的要求之后。 你可以试试这个单行:
SELECT REPLACE(RTRIM(@name), ' ', '-') + SUBSTRING(@name, LEN(RTRIM(@name)) + 1, LEN(@NAME))
但我建议您将其放入用户定义的函数中。
答案 2 :(得分:1)
假设SQL Server:
update TABLE set column = replace (column, ' ','-')
答案 3 :(得分:0)
SELECT REPLACE(field_name,' ','-');
编辑:在跳过尾随空格的要求之后。你可以试试这个单行:
SELECT REPLACE(RTRIM(@name), ' ', '-') + SUBSTRING(@name, LEN(RTRIM(@name)) + 1;