日期:2014-05-17  浏览次数:20729 次

SQL查询多值字段中的值
一张employee表,字段有emp_no,emp_name,emp_degree,其中emp_degree字段是学位,因为一个员工可能有多个学位,数据库设计时采用了把多个学位的值用逗号分隔存在emp_degree字段中。现在我想问的是如何用sql语句查询出具有a学位的员工。
示例数据:
emp_no   emp_name  emp_degree
1         keven     a,b,c
2          nike     a,b
3          mical     b
这条sql语句如何写呢?
------解决方案--------------------

select * from tb where emp_degree like'%a%'

or

select * from tb where charindex('a',emp_degree)>0

------解决方案--------------------
select * from tb where ',' + emp_degree + ',' like'%,a,%'

or

select * from tb where charindex(',a,',',' + emp_degree + ',')>0



------解决方案--------------------
select * from tb where charindex(','+'a'+',',','+emp_degree+',')>0

------解决方案--------------------
引用:
SQL code
select * from tb where ',' + emp_degree + ',' like'%,a,%'

or

select * from tb where charindex(',a,',',' + emp_degree + ',')>0

+
------解决方案--------------------


declare @t table(emp_no int,emp_name varchar(10),emp_degree varchar(10))
insert into @t select 1,'keven','a,b,c' union all
select 2,'nike','a,b' union all
select 3,'mical','b';

select a.emp_no,a.emp_name,b.v1 from (
select emp_no,emp_name,cast('<root><d>'+REPLACE(emp_degree ,',','</d><d>')+'</d></root>' as xml) as val from @t
) a
outer apply (
select  v1=N.v.value('.','varchar(10)') from a.val.nodes('/root/d') N(v)
) b

/*
emp_no      emp_name   v1
----------- ---------- ----------
1           keven      a
1           keven      b
1           keven      c
2           nike       a
2           nike       b
3           mical      b
*/

------解决方案--------------------
 #8楼 得分:0回复于:2011-09-21 16:55:11SQL code

 select a.emp_no,a.emp_name,b.v1 from (
    select emp_no,emp_name,cast('<root><d>'+REPLACE(emp_degree ,',','</d><d>')+'</d></root>' as xml) as val from @t