如果没有零,则为返回值添加零

时间:2013-07-08 15:35:39

标签: sql-server sql-server-2008 tsql

以下查询从我的数据库返回以下示例数据。

select mobileno
from Person

样本结果:

775623655
0758956556
0756899955
777325656

如果返回值中没有0,如何在前面添加0?

5 个答案:

答案 0 :(得分:3)

SELECT CASE LEFT(mobileno,1) 
    WHEN '0' THEN mobileno
    ELSE '0' + isNull(mobileno,'')
    end as mobileno
FROM Person 

答案 1 :(得分:2)

select right('0000000000' + mobileno, 10) mobileno from Person

答案 2 :(得分:1)

使用REPLICATE

SELECT 
  RIGHT(REPLICATE('0', 10) + CAST(mobileno AS VARCHAR(10)), 10) AS mobileno
FROM person;

请在此处查看:

答案 3 :(得分:1)

你想确保它总是以0开头,长度是10吗?一种方式:REPLACE

SELECT REPLACE(STR(mobileno, 10, 0), ' ', '0')
FROM dbo.Person

DEMO

答案 4 :(得分:1)

嘿检查以下查询。你可以这样做:

declare @table table (temp VARCHAR(MAX))

insert into @table values('775623655')
insert into @table values('0758956556')
insert into @table values('0756899955')
insert into @table values('777325656')

SELECT RIGHT('000000000' + temp , 10)
FROM @table

SqlFiddle