zoukankan      html  css  js  c++  java
  • 逗号分隔的字符串转成表格参与IN条件查询

    返回值为'1,2,3,4,5,6,7',是一个字符串,如果要用IN 查询的话sql认为这是一个完整的字符串,需要将内容分隔转换变成table

    定义函数如下:

    create Function sysfStrToTable(@str varchar(1000)) 
    Returns @tableName Table 
    ( 
    str2table varchar(50) 
    ) 
    As 
    --该函数用于把一个用逗号分隔的多个数据字符串变成一个表的一列,例如字符串'1,2,3,4,5' 将变成一个表
    Begin 
    set @str = @str+',' 
    Declare @insertStr varchar(50) --截取后的第一个字符串 
    Declare @newstr varchar(1000)--截取第一个字符串后剩余的字符串 
    set @insertStr = left(@str,charindex(',',@str)-1) 
    set @newstr = stuff(@str,1,charindex(',',@str),'') 
    Insert @tableName Values(@insertStr) 
    while(len(@newstr)>0) 
    begin 
    set @insertStr = left(@newstr,charindex(',',@newstr)-1) 
    Insert @tableName Values(@insertStr) 
    set @newstr = stuff(@newstr,1,charindex(',',@newstr),'') 
    end 
    Return 
    End
    

      

     调用:

    declare @str as varchar(100)
    set @str='1,2,3,4,6'
    
    select * from table1
    where 
    ID IN (SELECT * FROM  dbo.sysfStrToTable(@str) )
    

      

  • 相关阅读:
    论语言思维的差异
    lua经典问题
    跳槽的故事
    未来一年计划
    腾讯面试题 找重复的数
    nodejs学习
    node记录
    mysql 常用总结
    ubuntu 服务器搭建汇总
    ubuntu下安装golang
  • 原文地址:https://www.cnblogs.com/crrc/p/11280490.html
Copyright © 2011-2022 走看看