zoukankan      html  css  js  c++  java
  • sql server 中将由逗号“,”分割的一个字符串,转换为一个表,并应用与 in 条件

    select * from tablenmae where id in(1,2,3)

    这样的语句和常用,但是如果in 后面的 1,2,3是变量怎么办呢,一般会用字符串连接的方式构造sql语句

    string aa="1,2,3";

    string sqltxt="select * from tablename where id in ("+aa+")";

    然后执行 sqltxt

    这样的风险是存在sql注入漏洞。那么如何在 in 的条件中使用变量呢?可以把形如“1,2,3”这样的字符串转换为一个临时表,这个表有一列,3行,每一行存一个项目(用逗号分隔开的一部分)

    该函数可以这样写:

    create Function StrToTable(@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

    然后sql语句就可以这样了

    declare str vchar(100)

    set str='1,2,3'

    select * from tablename where id in (select str2table from StrToTable(@str) )
  • 相关阅读:
    PHP实现最简单爬虫原型
    xcache 安装与配置
    fckeditor[php]上传文章内容图片插件[提供技术支持]
    使用PHP创建一个REST API(Create a REST API with PHP)
    php错误处理
    PHP二维数组排序
    鼠标指针经过时整行变色的表格
    java net unicode / native2ascii / url decode / url encode / UTF8 / js url code
    java protocol / patent
    framework junit
  • 原文地址:https://www.cnblogs.com/shenyixin/p/2154115.html
Copyright © 2011-2022 走看看