2

My SQL Server table has a column defined as:

TicketNo varchar(5)

The rows in this table are inserted by some bulk load files from different sources.

Now, depending on who prepared the bulk load input files, sometimes TicketNo has leading 0s, sometimes not.

How can I enforce INSERTS to the table so that TicketNo will always be set with leading zeros, something like:

TicketNo = RIGHT('00000'+TicketNo, 5)
2
  • Did you try this SQL - insert into table (ticketno,...) values (RIGHT('00000'+@TicketNo, 5),...); ? Commented Mar 26, 2013 at 18:03
  • I have no control as to the actual INSERTs, they are done outside our group. At present I sometime run an UPDATE to set them correctly. What I was thinking it some kind of constraint to enforce the leading zeros automatically, if that is at all possible. Commented Mar 26, 2013 at 18:10

2 Answers 2

2

You can use a char(5) column with a check constraint.

create table YourTable
(
  TicketNo char(5) check (patindex('%[^0-9]%', TicketNo) = 0)
)

Update:

Using this answer by Martin Smith it could look like this instead to make sure there are only 0-9 allowed.

create table YourTable
(
  TicketNo char(5) collate Latin1_General_CS_AS check (patindex('%[^0123456789]%', TicketNo) = 0) 
)
Sign up to request clarification or add additional context in comments.

10 Comments

char(5) seems like a good idea, but the check constraint should probably take length into account as well, so something like LEN(T) = 5 AND T NOT LIKE '%[^0-9]%'
@JasonWhisman Not at all necessary with a char(5). It will always be 5.
This will cause inserts to fail if TicketNo is not 5 digits. That's one interpretation of "enforce". If the OP wants automatically update the value upon insert or update, rather than fail the operation, he might need an Insert,Update Trigger.
@GilM Only OP knows :). If that was the case I would personally turn the column into an integer with check < 100000 and a computed column that pads the zeros.
Also, and this is just a pet peeve of mine.. LEN(TicketNo) will not always be 5, even if TicketNo is a char(5) because LEN, for some idiotic reason, does not count trailing spaces. DATALENGTH(TicketNo) would always be 5...But, I'm not bitter. :-)
|
1

How you enforce it is a tricky question. My first through would be to create a stored procedure and force all inserts to take place through that. Then you could use rs's solutions.

Other than that you can create an insert/update trigger that checks for leading zeros.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.