简体   繁体   English

搜索varchar列,仅适用于匹配的数值

[英]Search varchar column, only on match numeric values

I have a column ( PRODUCTNUMBER ) of type VARCHAR that can contain data like this: 我有一个VARCHAR类型的列( PRODUCTNUMBER ),可以包含如下数据:

SEC123456
SEC-123456
12-35-46
123456

Is it's possible to run a SQL Server query where I only send '123456' as my search data and will get a match for all of the rows that PRODUCTNUMBER has this data in it (even if PRODUCTNUMBER data contain characters like 'SEC123456' )? 是否可以运行SQL Server查询,在该查询中我仅发送“ 123456”作为搜索数据,并且将获得PRODUCTNUMBER包含该数据的所有行的匹配项(即使PRODUCTNUMBER数据包含诸如'SEC123456''SEC123456' )?

First Create Function to Extract Numeric Value 首先创建函数以提取数值

CREATE FUNCTION dbo.udf_GetNumeric
(@strAlphaNumeric VARCHAR(256))
RETURNS VARCHAR(256)
AS
BEGIN
DECLARE @intAlpha INT
SET @intAlpha = PATINDEX('%[^0-9]%', @strAlphaNumeric)
BEGIN
WHILE @intAlpha > 0
BEGIN
SET @strAlphaNumeric = STUFF(@strAlphaNumeric, @intAlpha, 1, '' )
SET @intAlpha = PATINDEX('%[^0-9]%', @strAlphaNumeric )
END
END
RETURN ISNULL(@strAlphaNumeric,0)
END
GO

then 然后

select * from TableName where dbo.udf_GetNumeric(PRODUCTNUMBER) like '%123456%'

try this 尝试这个

For the case of contiguous characters: 对于连续字符:

select * from t where productnumber like '%123456%'

would work. 会工作。 If it's just '-' in the data you can use replace(productnumber, '-', ''). 如果数据中只是“-”,则可以使用replace(productnumber,'-','')。 But if it could be many other non-numeric characters, you want something like: 但是,如果可能有许多其他非数字字符,则需要类似以下内容:

SQL to return field with non-numeric characters removed in MySQL SQL返回MySQL中已删除非数字字符的字段

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM