----------------------------------------------------------------
-- Author  :DBA_Huangzj(發糞塗牆)
-- Date    :2014-01-24 12:46:51
-- Version:
--      Microsoft SQL Server 2012 (SP1) - 11.0.3128.0 (X64) 
-- Dec 28 2012 20:23:12 
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: )
--
----------------------------------------------------------------
--> 测试数据:[huang]
if object_id('[huang]') is not null drop table [huang]
go 
create table [huang]([ID] int,[postlevelIDs] varchar(5))
insert [huang]
select 1,'[3]' union all
select 2,'[3,5]' union all
select 3,'[2,6]' union all
select 4,'[]'
--------------开始查询--------------------------select * from [huang] 
WHERE CHARINDEX(','+'3'+',', ','+SUBSTRING([postlevelIDs],2,LEN([postlevelIDs])-2)+',')>0
----------------结果----------------------------
/* 
ID          postlevelIDs
----------- ------------
1           [3]
2           [3,5]*/

解决方案 »

  1.   

    试试这个:
    if object_id('[tb]') is not null drop table [tb]
    go 
    create table [tb]([ID] int,[postlevelIDs] varchar(5))
    insert [tb]
    select 1,'[3]' union all
    select 2,'[3,5]' union all
    select 3,'[2,6]' union all
    select 4,'[]'
    goselect *
    from tb
    where CHARINDEX(','+'3'+',' , ','+replace(REPLACE([postlevelIDs],'[',''),']','')+',') > 0
    /*
    ID postlevelIDs
    1 [3]
    2 [3,5]
    */
      

  2.   

    为什么要那么复杂呢
    select * from tb where postlevelIDs like '%3%'
      

  3.   

    直接用like会有问题的。比如[3],[13]select * from tb where postlevelIDs like '%3%'就会把[3],[13]都返回,那就有问题了
      

  4.   

    [13,23]还足矣?
    like足矣你不会活用?
    like '%3%'
    其中postlevelIDs由 postlevelID 通过','号隔开,前后用[]号包括起来
    请问怎样查询出比如postlevelIDs包含 3的记录?
    4存在几种可能?'[3,' 一种 ',3,' 一种 ',3]' 一种[3]一种
    4种可能 写or 4次like 不足矣?