有字符型变量 str="1,2,3,4,5" 
SQL2000下有数据表table 如下: id,id2都是int型
id  id2
1    2
2    2
3    3
4    7
现在要查询table 中查询id2 包含在str中的记录
select * from table where id2 in ('"&str&"')
提示将"1,2,3,4,5"转换为INT型时发生错误
如何将字符串先转成集合?

解决方案 »

  1.   

    select * from table where charindex(','+rtrim(id2)+',', ','+@str+',')>0
      

  2.   

    exec ('select * from table where id2 in ('+ @str +')')
      

  3.   

    select * from [Table] where ','+@str+',' like '%,'+ltrim(id2)+',%'
      

  4.   


    SELECT* FROM TABLE WHERE CHARINDEX(','+ltrim(rtrim(id2))+',', ','+@str+',')>0
      

  5.   

    动态SQL语句就可以
    exec ('select * from tb where id2 in ('+ @str +')')
      

  6.   

    exec ('select * from tb where id2 in ('+ @str +')')
      

  7.   


    /*按照符号分割字符串*/
    create function [dbo].[m_split](@c varchar(2000),@split varchar(2))   
      returns @t table(col varchar(200))   
      as   
        begin   
          while(charindex(@split,@c)<>0)   
            begin   
              insert @t(col) values (substring(@c,1,charindex(@split,@c)-1))   
                set @c = stuff(@c,1,charindex(@split,@c),'') 
               -- SET @c = substring(@c,charindex(' ',@c)+1,len(@c))     
            end   
          insert @t(col) values (@c)   
          return   
    end
    godeclare @str nvarchar(200)
    set @str='1,2,3,4,5' ;declare @table table (id int,id2 int)
    insert into @table
    select 1,2 union all
    select 2,2 union all
    select 3,3 union all
    select 4,7
    select * from @table
    /*
    id          id2
    ----------- -----------
    1           2
    2           2
    3           3
    4           7
    */
    select * from @table where id2 in (select col from dbo.[m_split](@str,','))
    /*
    id          id2
    ----------- -----------
    1           2
    2           2
    3           3
    */