Reputation: 839
I need to insert a value into this database field but it needs to be padded with leading 0s if this number has less than 9 digits, as an example, 12345
should be converted to 000012345
before inserting it into the database. I am trying this, but it's not working, I can not use stored procedure, is it possible?
insert into my_table (right('00000000' + cast(account as char(8)), 8)) values ('12345')
Upvotes: 0
Views: 294
Reputation: 10908
Use STR() to convert numbers to right-justified strings. Procedures that use CONVERT(varchar(8),...) can't be parameterized because varchar(@size) is invalid.
SELECT REPLACE(STR(12345,8),' ','0')
Upvotes: 0
Reputation: 48826
Two issues here:
Try this:
INSERT INTO my_table (Account)
VALUES (RIGHT('00000000' + CAST(12345 AS VARCHAR(8)), 8))
Upvotes: 3