Search code examples
sql-servert-sqlsubstring

Argument data type varchar is invalid for argument 2 of substring function


I'm trying to put 2x'-' in phone number and I'm getting the following error

Argument data type varchar is invalid for argument 2 of substring function.

I'm working on Tsql. I also try 'mid' function - no results. I need a result like '123-456-789'.

declare @tel nvarchar(20) = 123456789
set @tel = (select left (@tel, '3'))+'-'+(select substring (@tel, '4','3'))+'-'+(select right (@tel, '3'))
select @tel

Solution

  • Your Query modified as below

    declare @tel nvarchar(20) = '123456789'
    set @tel = (select left (@tel, 3))+'-'+(select substring (@tel, 4,3))+'-'+(select right (@tel, 3))
    select @tel
    

    can Re write as below

    declare @tel nvarchar(20) = '123456789'
    set @tel = left (@tel, 3)+'-'+substring (@tel, 4,3)+'-'+ right (@tel, 3)
    select @tel