July 21, 2010 at 8:45 am
I have an account number field that has an 10 digit account number in it. What I need to do is add dashes in those accounts numbers. For example, if my account number is 1111111111, I want to update that account to say 111-11111-11. What is the best option of doing this?
July 21, 2010 at 8:47 am
So far, I'm able to select the first three and then add an dash like this:
SELECT LEFT(ACCOUNTNUMBER, 3)+'-'
from BILLING.ACCOUNT
But I'm not sure where to go from here. Should I use a STUFF query?
July 21, 2010 at 9:04 am
Thank you! This worked perfectly!
SELECT SUBSTRING(ACCOUNTNUMBER, 1, 3)+'-'+SUBSTRING(ACCOUNTNUMBER, 4, 5)+'-'+SUBSTRING(ACCOUNTNUMBER, 9, 2)
FROM BILLING.ACCOUNT
July 21, 2010 at 9:10 am
You might want to look at STUFF also. If you use this, it might be easier to add the dashes from back to front.
Wayne
Microsoft Certified Master: SQL Server 2008
Author - SQL Server T-SQL Recipes
July 21, 2010 at 9:14 am
You can also learn about another two string T-SQL functions:
SELECT LEFT(ACCOUNTNUMBER, 3) + '-' + SUBSTRING(ACCOUNTNUMBER, 4,5) + '-' + RIGHT(ACCOUNTNUMBER,2)
FROM BILLING.ACCOUNT
However, it looks like you are going to use this query for output to the client app or report. If that is true, than your best o[ption to do formatting in app or report itself. Using SQLServer to format data for the representation is not the best idea...;-)
July 21, 2010 at 12:09 pm
I agree with Joe that this should be done in the presentation/application layer. I understand that sometimes this is beyond your control. If you absolutely must accomplish this via TSQL, I recommend the Stuff function, as it is very compact and very clean.
DECLARE @t TABLE(
col VARCHAR(10)
);
INSERT INTO @t VALUES ('1234567890');
INSERT INTO @t VALUES ('1111111111');
SELECT STUFF(STUFF(col,4,0,'-'),10,0,'-')
FROM @t
July 21, 2010 at 12:21 pm
Adam Haines (7/21/2010)
Agreed... sometimes there is no GUI.
--Jeff Moden
Change is inevitable... Change for the better is not.
Viewing 8 posts - 1 through 7 (of 7 total)
You must be logged in to reply to this topic. Login to reply