根据sql server中的值消除记录

时间:2016-06-08 11:00:43

标签: sql sql-server database tsql

我有一个table,如下所示,

id    record

1    5000tax
2    tax5000
3    tax5001
4    taxpro
5    val5005

我需要检索以字母开头的记录。我写下面的查询

select id, record, right(record,4) as code
from table
where left(record,1) like 'A' and 'Z'

输出:

id  record   code

2   tax5000  5000
3   tax5001  5001
4   taxpro   xpro
5   val5005  5005

此处我不想包含其中没有任何数字的records。 即xpro。

我在下面写了一下查询

  select id, record, right(record,4) as code
    from table
    where left(record,1) like 'A' and 'Z'
    and record between '0' and '9'

它没有提供任何输出。

感谢您的帮助

(P.S:表中禁用了全文搜索属性)

5 个答案:

答案 0 :(得分:3)

您可以将[0-9]LIKE

一起使用
select id, record, right(record, 4) as code
from table
where record like '[A-Z]%'
  and record like '%[0-9]%';

或者如果它最后总是有四位数字,那么:

select id, record, right(record, 4) as code
from table
where record like '[A-Z]%'
  and record like '%[0-9][0-9][0-9][0-9]';

答案 1 :(得分:2)

您正在寻找between,而不是like

select id, record, right(record,4) as code
from table
where left(record, 1) between 'A' and 'Z';

或者,在SQL Server中,您可以执行以下操作:

where record like '[A-Z]%'

或者,如果您担心大写和小写:

where record like '[A-Za-z]%'

答案 2 :(得分:0)

你可以试试这个。

SELECT id, record 
FROM table
WHERE record BETWEEN 'a%' AND 'z%' 
      AND regexp_like(record,'[[:digit:]]')

答案 3 :(得分:0)

DECLARE @StartLetter TABLE (Id INT,Record VARCHAR(10))

INSERT INTO @StartLetter VALUES
(1,'5000tax'),
(2,'tax5000'),
(3,'tax5001'),
(4,'taxpro'),
(5,'val5005')

SELECT * FROM @StartLetter WHERE Record LIKE '[A-Z]%' 

答案 4 :(得分:0)

我重写了query as,

  select id, record, right(record,4) as code
  from table
  where left(record,1) between 'A' and 'Z'
  and record like '%[0-9]%'