0

I have created small function using T-SQL which takes one input parameter as phone number and returns area code from it. Function compiles successfully but getting only first digit of the phone number instead of three digits.

Refer below code:-

create or alter function getareacode (@phoneno as nvarchar)
returns nvarchar(10)
with schemabinding 
as
begin
  declare @areacode as nvarchar(10);
  select top(1) @areacode = value from string_split(@phoneno,'-');
  return @areacode;
end;

select dbo.getareacode( N'123-456-789');  
1
  • LEFT(@phoneno, PATINDEX('%-%', @phoneno)-1) can also get you everything before the first - Commented Aug 15, 2017 at 23:09

1 Answer 1

4

(@phoneno as nvarchar) will generate the 1st character only

try

(@phoneno as nvarchar(50))

However, the split may not be necessary

Try the following. It may be more performant

Declare @S nvarchar(50) = '123-456-789'

Select left(replace(replace(replace(@S,'-',''),'(',''),')',''),3)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.