当前位置: 代码迷 >> Sql Server >> SQL循环比较的有关问题
  详细解决方案

SQL循环比较的有关问题

热度:67   发布时间:2016-04-24 20:28:10.0
SQL循环比较的问题

表teset
字段:
ID PY
1 A
2 B
3 A
4 D
5 C
6 B
7 1
8 A
9 A
10 A

Has="A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z"


主要想实现的功能:
用ASP中的Has字符串与表teset中PY字段进行比较,如果字段中存在这个字母,就用A标签显示,如果不存在就直接输出,如果是数字,就输出数字,具体如下:

'比如PY字段中有A
Response.Write "<a target=""_self"" href=""#a"">A</a>"
'如果没有A
Response.Write "A"
'如果有数字,则直接输出
Response.Write "1"

------解决方案--------------------
加distinct 就可以了

create table #tb(ID int,PY char(1))
insert into #tb
select 1,'A'
union all select 2,'B'
union all select 3,'A'
union all select 4,'D'
union all select 5,'C'
union all select 6,'B'
union all select 7,1
union all select 8,'A'
union all select 9,'A'
union all select 10,'A'

declare @Has varchar(1000)
set @Has='A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z'
select distinct case when charindex(','+cast(PY as varchar)+',',','+@Has+',')=0 then PY 
else '"<a target=""_self"" href=""#a"">'+cast(PY as varchar)+'</a>"' end as result
from #tb
drop table #tb

--结果
/*
"<a target=""_self"" href=""#a"">A</a>"                             
"<a target=""_self"" href=""#a"">B</a>"                             
"<a target=""_self"" href=""#a"">C</a>"                             
"<a target=""_self"" href=""#a"">D</a>"                             
  相关解决方案