日期:2014-05-18  浏览次数:20522 次

求SELECT LIKE特殊实例用法
有一字符串如下:
@cc='2010,2011,2012,2013'


我想查询SELECT * FROM Order WHERE Years Like '2010%' OR Years Like '2011%' OR Years Like '2012%'...
@cc里面可能还会有更多的内容,也就是动态的

请问高手如何写存储过程??????

------解决方案--------------------
SQL code
create procedure pr_test(
 @str varchar(1200)='2010,2011,2012,2013'
 )
 as
 declare @tmp varchar(1200),@mid varchar(1200),@sql varchar(max) 
set @tmp=''
set @mid=REPLACE(@str,',','')
set @sql='SELECT * FROM Order WHERE '
declare @count int ,@len int 
select @len=len(@str)-len(REPLACE(@str,',',''))
set @count=0

while @len-@count>=0
begin
    if(LEN(@TMP)=0)
        BEGIN
            SET @tmp= ' years like ''' +substring(@mid,1,4)+'%'''
            set @mid=SUBSTRING(@mid,5,LEN(@mid)-4);
        END
        ELSE
        BEGIN
        set @tmp=@tmp+' or  years like '''+substring(@mid,1,4)+'%''  '
        set @mid =SUBSTRING(@mid,5,LEN(@mid)-4);
        END
        set @count=@count+1
end
set @sql=@sql+ @tmp 
select @sql --1
exec(@sql)
/* --1 打印出的结果是,最后将 select @sql 注释掉
SELECT * FROM Order WHERE  years like '2010%' or  years like '2011%'   or  years like '2012%'   or  years like '2013%'  
最后 将 @str varchar(1200)='2010,2011,2012,2013' 的参数换成你的即可*/