简体   繁体   中英

Left pad varchar to certain length in sql server

I want to left pad int number with 12 digits as 0 and starting with character as 'P'

Eg if number is 345 Then output should be ' P00000000345 '

My Code :

Declare @a int
Set @a =8756
Select Right('P00000000000' +Cast(@a As Varchar(11)),12)

DB : SQL SERVER 2008

Try

Declare @a int
Set @a =8756
Select 'P'+Right('00000000000' +Cast(@a As Varchar(11)),11)

You're mostly correct, but should apply the P as a separate step:

Declare @a int
Set @a =8756
Select 'P' + Right('000000000000' +Cast(@a As Varchar(11)),12)

Try this

Declare @a int
Set @a =8756
Select 'P' + REPLACE(STR(@a, 11), SPACE(1), '0')

Demo: http://sqlfiddle.com/#!3/d41d8/18547

Change

Select Right('P00000000000' +Cast(@a As Varchar(11)),12)

to

Select 'P' + Right('00000000000' +Cast(@a As Varchar(11)),11)

SQL Fiddle DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM