简体   繁体   English

如何确定字段在SQL Server 2008 R2中是否具有前导零?

[英]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

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): 另一种方法是使用LIKE (此解决方案可支持SARG,如果列具有索引,则应具有更好的性能):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何确定Microsoft SQL Server 2008 R2的实例 - How can i determine the instance of my Microsoft SQL Server 2008 R2 如何查看SQL Server 2008是否为R2版本? - How can I see if SQL Server 2008 is the R2 release? 如何在我的列 (SQL Server 2008 R2) 上创建唯一约束? - How can I create a unique constraint on my column (SQL Server 2008 R2)? 如何修改SQL Server 2008 R2 FK的父表 - How i can modify the Parent table for my Sql server 2008 r2 FK 如何强制 SQL Server 2008 R2 中的整个表的列唯一? - How can I force a column to be unique for an entire table in SQL Server 2008 R2? 如何只将字符串中的数字作为SQL Server中的计算列而不带前导零? - How can I get only numbers from a string as a computed column in SQL Server with no leading zeroes? 如何在SQL Server 2008 R2中添加具有其他列值作为默认值的列? - How to add a column which has another column value as default value in SQL Server 2008 R2? 是否可以在SQL Server 2008 r2的服务器级别添加用户定义函数? - Can I add a User Defined Function at the server level in SQL Server 2008 r2? SQL Server 2008 R2无法登录 - SQL Server 2008 r2 can't login 无法在Windows 8中使用SQL Server 2008 R2创建数据库 - Can't create database in Windows 8 with SQL Server 2008 R2
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM