Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert leading zero in SQL Server

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?

like image 847
Matthew Sarmiento Avatar asked Mar 06 '13 00:03

Matthew Sarmiento


People also ask

How do you add leading zeros to a string?

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.

How do I Zero a prefix in SQL?

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.

How can I pad a value with leading zeros?

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.


2 Answers

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
like image 144
Aaron Bertrand Avatar answered Sep 22 '22 18:09

Aaron Bertrand


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)
like image 42
Trey Mack Avatar answered Sep 20 '22 18:09

Trey Mack