日期:2014-05-16  浏览次数:20341 次

字段中有分隔符,如何查询符合条件的记录
我的数据表中有一个字段,存储的是1,2,3,10,12这样的记录,有没有办法查询出记录中使用","进行分隔成单个数字后,查询中字段中分隔出来数字符合条件的记录;

字段A
1,2,5,16,18
2,4,5,7,12
9,3,4,5
3,8,9

查询出字段A中,使用","分隔后有3的记录,请大侠指导一下能否直接通过SQL来实现这种查询,数字出现的位置是不固定的
------解决方案--------------------
----------------------------------------------------------------
-- Author  :DBA_HuangZJ(发粪涂墙)
-- Date    :2014-03-06 07:50:04
-- Version:
--      Microsoft SQL Server 2008 R2 (RTM) - 10.50.1600.1 (X64) 
-- Apr  2 2010 15:48:46 
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: ) (Hypervisor)
--
----------------------------------------------------------------
--> 测试数据[huang]
if object_id('[huang]') is not null drop table [huang]
go 
create table [huang]([A] nvarchar(22))
insert [huang]
select '1,2,5,16,18' union all
select '2,4,5,7,12' union all
select '9,3,4,5' union all
select '3,8,9'
--------------生成数据--------------------------

select * 
from [huang]
WHERE CHARINDEX(',3',A)>0
----------------结果----------------------------
/* 
A
----------------------
9,3,4,5

*/

------解决方案--------------------
位置不固定?用
where charindex(',3,',','+ltrim(A)+',')>0