This is the code for selecting with leading zeros:
SELECT RIGHT('00000'+ CONVERT(VARCHAR,Asset_No),6)
FROM schemaAsset.SystemDefined
How can I insert a value to the column Asset_no with leading zeros?
Example is I am only inserting "1" to the column Asset_no, but in the code, it will insert "000001". And also when I insert two digits like 26, it will insert as "000026". The length does not change. Is this possible in SQL Server?
Left and Right padding Integer and String in Java You just need to add "%03d" to add 3 leading zeros in an Integer. Formatting instruction to String starts with "%" and 0 is the character which is used in padding. By default left padding is used, 3 is the size and d is used to print integers.
The safest way is probably to only add zeroes when the length of the column is 1 character: UPDATE Table SET MyCol = '0' + MyCol WHERE LEN(MyCol) = 1; This will cover all numbers under 10 and also ignore any that already have a leading 0.
To pad an integer with leading zeros to a specific length To display the integer as a decimal value, call its ToString(String) method, and pass the string "Dn" as the value of the format parameter, where n represents the minimum length of the string.
One way to do this is with an INSTEAD OF
trigger.
USE tempdb;
GO
CREATE TABLE dbo.whatever
(
Asset_No VARCHAR(6)
);
GO
CREATE TRIGGER dbo.fix_whatever
ON dbo.whatever
INSTEAD OF INSERT
AS
BEGIN
SET NOCOUNT ON;
INSERT dbo.whatever(Asset_No /*, other columns */)
SELECT RIGHT('000000' + CONVERT(VARCHAR(6), Asset_No), 6)
/*, other columns */
FROM inserted;
END
GO
INSERT dbo.whatever(Asset_No) SELECT '22';
GO
SELECT Asset_No FROM dbo.whatever;
GO
Results:
Asset_No
--------
000022
If you want to do the padding in SQL Server, you can do something like this with your INSERT statement:
DECLARE @Asset_no INT = 12;
INSERT INTO schemaAsset.SystemDefined (Asset_no)
SELECT RIGHT('00000'+ CONVERT(VARCHAR(6),@Asset_No),6)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With