[英]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. 我在表上有一个varchar字段,我需要知道是否有办法知道它是否以给定的零开始。
Do I have to use variables or if-else? 我必须使用变量还是if-else?
You can use LEFT
to get leading text and compare with zeros string: 您可以使用
LEFT
获取前导文本并与零字符串进行比较:
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
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;
Another way is to use LIKE
(this solution is SARG-able and should have better performance if column has index): 另一种方法是使用
LIKE
(此解决方案可支持SARG,如果列具有索引,则应具有更好的性能):
SELECT *
FROM your_table
WHERE col LIKE REPLICATE('0', @number) + '%'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.