特定范围内字符串的Numberpart

时间:2014-10-14 11:53:21

标签: sql sql-server

我正在使用SqlServe,我需要获取字符串的一部分在特定numberRange内的所有行。

例如,我在列uniqueStringID:

  • BE09 Mytest
  • BE10 Mytest
  • CE101 Mytest
  • CE300 Mytest

我想得到所有行,其中uniqueStringID中的数字(数字必须位于空格之前)介于(包括)10和101之间

结果将是:

  • BE10 Mytest
  • CE101 Mytest

我的问题是这可能只用SQL或者我需要一个存储过程吗?如果前者将如何SQL?

3 个答案:

答案 0 :(得分:1)

drop table #t
create table #t(id varchar(100))
insert into #t values('BE09 Mytest'),
('BE10 Mytest'),
('CE101 Mytest'),
('CE300 Mytest'),
('CE450595 Mytest')


select id,cast(substring(id,patindex('%[0-9]%',id),patindex('%[a-z0-9] [a-z]%',id)-1) as int) from #t where cast(substring(id,patindex('%[0-9]%',id),patindex('%[a-z0-9] [a-z]%',id)-1) as int) between 10 and 101

FIDDLE DEMO

FIDDLE DEMO WITH FEW MORE TEST CASES

答案 1 :(得分:0)

首先在sql server中创建函数

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

然后使用以下查询获取结果

SELECT * FROM
(
SELECT uniqueStringID,dbo.udf_GetNumeric(uniqueStringID) AS NumuniqueStringID 
 FROM YourTableName
) a
WHERE NumuniqueStringID >=10 and NumuniqueStringID<=101

答案 2 :(得分:0)

您可以使用substring来分配您的号码进行过滤(在所有示例中,字符串最后的长度始终相同):

select cast(substring(uniqueStringID, 3, len(uniqueStringID)-9) as int)