SQL之间的标量变量值和

时间:2012-03-22 12:49:00

标签: sql sql-server-2005-express

表'数据'中的

'名称'

"type12pen105A"
"type12pen110A"
"type12pen121B"

Declare @n int;

select Names From Data
where Names ='type12pen'+cast(@n between 100 and 110 as varchar)+'A'

My Required out put是

"type12pen105A"
"type12pen110A"

3 个答案:

答案 0 :(得分:1)

SELECT Names
FROM Data
WHERE Names LIKE 'type12pen%' 
AND CAST(SUBSTRING(Names,10,3) AS INT) BETWEEN 100 AND 110
AND RIGHT(Names,1) = 'A'

答案 1 :(得分:0)

declare @Data table(
  name varchar(32)
)

insert into @Data values('type12pen105A')
insert into @Data values('type12pen110A')
insert into @Data values('type12pen121B')
insert into @Data values('book11jil124C')


select name
from @Data
where cast(substring(name, 10, 3) as int) between 100 and 110
      and name like 'type12pen%'
      and right(name, 1) = 'A'

如果这是一个大型表,您可能会通过对数据运行流程并将产品名称的不同方面拆分为单个字段并查询这些表来提供更好的服务。使用substringright意味着您无法获得索引的好处。

答案 2 :(得分:0)

根据您提供的信息,这很难看,但应该有效:

create table #data
(
    names varchar(50)
)

insert into #data values('type12pen105A')
insert into #data values('type12pen101A')
insert into #data values('type12pen112A')
insert into #data values('type12pen120A')
insert into #data values('type12pen110A')
insert into #data values('type12pen106A')
insert into #data values('type12pen110C')
insert into #data values('type12pen110D')
insert into #data values('type12pen110E')
insert into #data values('type12pen121B')

SELECT Names
FROM #Data
WHERE Names LIKE 'type12pen%' 
AND RIGHT(Names,1) = 'A'
AND replace(replace(names, 'type12pen', ''), 'A', '') BETWEEN 100 AND 110 

drop table #data

结果:

type12pen105A
type12pen101A
type12pen110A
type12pen106A