Insert character into SQL string

瘦欲@ 提交于 2019-12-19 19:55:33

问题


I have an nvarchar column I need to insert a hyphen at fixed points within the string. The hyphen need to go between the rightmost character and the next, and again in the 3rd position from the right, such as: column value is

0000050704 

and I need it to be

0000050-70-4

or value is

0555256321 

and it should be

0555256-32-1

Can't see how this is done. Can anyone give me a little help?


回答1:


Assuming the strings can be a variable length, you'll need to use REVERSE() or lots of nasty looking LEN() values in your expression.

declare @txt varchar(100) = '0000050704'

--If using SQL Server, the STUFF() function is your friend
select REVERSE(STUFF(STUFF(REVERSE(@txt), 2, 0, '-'), 5, 0, '-'))

--if not you'll need to concatenate SUBSTRING()s
select REVERSE(SUBSTRING(REVERSE(@txt), 1, 1) + '-' + SUBSTRING(REVERSE(@txt),2, 2) + '-' + SUBSTRING(REVERSE(@txt),4, LEN(@txt)))



回答2:


It depends on your SQL server. Please check the documentation on how to manipulate strings - I will suppose SUBSTRING function.

In MS SQL Server you can do sth. like this:

UPDATE YourTableName SET 
    YourFieldName = 
        SUBSTRING(YourFieldName, 1,7) + "-" + 
        SUBSTRING(YourFieldName, 7,2) + "-" +
        SUBSTRING(YourFieldName, 9,1)

This will split your field content in three parts and rebuild it with separators...

Before running the query I will suggest you try it as plain SELECT to see if it works as needed:

SELECT
    SUBSTRING(YourFieldName, 1,7) + "-" + 
    SUBSTRING(YourFieldName, 7,2) + "-" +
    SUBSTRING(YourFieldName, 9,1)
FROM YourTableName

Take care that the query is without WHERE condition and thus will affect ALL rows of your table.




回答3:


You can use this easy function:

CREATE FUNCTION [dbo].[SetHyphen] (@S varchar(50)) RETURNS varchar(52)
BEGIN
RETURN STUFF(STUFF(@S,LEN(@S)-2,0,'-'),LEN(@S)+1,0,'-')
END

For example:

select [dbo].[SetHyphen]('0000050704')
0000050-70-4


来源:https://stackoverflow.com/questions/17300683/insert-character-into-sql-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!