试图在sql server上找到字符串中的子字符串

时间:2014-02-06 03:35:22

标签: sql tsql scalar charindex

我已阅读过很多文章,其中包括stackoverflow,要查找子字符串,应使用以下内容:

IF CHARINDEX('mywoRD', @words) > 0
BEGIN
    -- DO SOMETHING
END

我正在尝试以下但是它不起作用它总是返回错误:

假设我有一个字符串'Basketball & Soccer',我正在尝试编写一个检查&符号的脚本并将其编码为&,因此它变为'Basketball & Soccer'我的问题是可能存在另一个在'Basketball & Soccer'的数据库中这样的人。

因此,当我运行我的脚本时,对于第二个脚本,它变为:

'Basketball & Soccer'

我正在尝试以下方法来清理它:

DECLARE @cleanparam as varchar(500)   

IF CHARINDEX('&',@myparameter) > 0 
BEGIN 
   -- if & is in the string skip and start with quotes
   SELECT @cleanparam = REPLACE(@myparameter,'"','"')   
END
ELSE
 BEGIN
      -- if not clean &'s and quotes and then continue with others
      SELECT @cleanparam = REPLACE(@myparameter,'&','&')   
      SELECT @cleanparam = REPLACE(@cleanparam,'"','"')   
 END

      SELECT @cleanparam = REPLACE(@cleanparam, '©', '©')
      SELECT @cleanparam = REPLACE(@cleanparam, '«', '«') 
       -- OTHERS HERE

2 个答案:

答案 0 :(得分:1)

如果无法保护脚本多次调用,则需要对其进行增强,首先将编码序列转换回值,然后再转换回序列。像这样:

  -- Convert back to symbols
  SELECT @cleanparam = REPLACE(@myparameter,'&','&')   
  SELECT @cleanparam = REPLACE(@cleanparam,'"','"')   
  etc...

  -- Convert symbols to escape sequences
  SELECT @cleanparam = REPLACE(@cleanparam,'&','&')   
  SELECT @cleanparam = REPLACE(@cleanparam,'"','"')   
  etc...

答案 1 :(得分:1)

试试这个

DECLARE @myparameter as varchar(500) 
set @myparameter = 'Basketball & Soccer & Volleyball'


DECLARE @cleanparam as varchar(500)
SELECT @cleanparam = REPLACE(@myparameter,'&amp;','&') --<----put some trick here :)
SELECT @cleanparam = REPLACE(@cleanparam,'&','&amp;')   
SELECT @cleanparam = REPLACE(@cleanparam,'"','&quot;') 
SELECT @cleanparam = REPLACE(@cleanparam, '©', '&copy;')
SELECT @cleanparam = REPLACE(@cleanparam, '«', '&laquo;') 

SELECT @cleanparam