简体   繁体   中英

How can I determine if a field has leading zeroes in SQL Server 2008 R2?

I have a varchar field on a table and I need to know if there is a way to know if it starts with a given number of zeroes.

Do I have to use variables or if-else?

You can use LEFT to get leading text and compare with zeros string:

DECLARE @number INT = 3;

SELECT *
FROM your_table
WHERE LEFT(column_name, @number) = REPLICATE('0', @number)
-- AND SUBSTRING(col, @number+1,1) <> '0'; If you need exact number of leading zeros

LiveDemo

Or when you need a flag:

SELECT *,
  [has_3_leading_zeros] = CASE 
                            WHEN LEFT(column_name, @number) = REPLICATE('0', @number) 
                            THEN 1 ELSE 0 END
FROM your_table;

LiveDemo2

Another way is to use LIKE (this solution is SARG-able and should have better performance if column has index):

SELECT *
FROM your_table
WHERE col LIKE REPLICATE('0', @number) + '%'

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