Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Tsql 在主字符串中查找并替换字符串_Tsql - Fatal编程技术网

Tsql 在主字符串中查找并替换字符串

Tsql 在主字符串中查找并替换字符串,tsql,Tsql,我试图在主字符串中找到一个字符串并将其删除 例如: @Main_text = 'some text some text... // remove text remove text \\ some text some text' 我想删除以下文本: // remove string remove string \\ of the main text 我试过的 declare @main_text varchar(255) = 'some text some text... // remove

我试图在主字符串中找到一个字符串并将其删除

例如:

@Main_text = 'some text some text... // remove text remove text \\ some text some text'
我想删除以下文本:

// remove string remove string \\ of the main text
我试过的

declare @main_text varchar(255) = 'some text some text... // remove text remove text \\ some text some text'

SELECT STUFF(@main_text, 
         charindex('//', @main_text), 
         charindex('\\', @main_text) , 
   ''); 

这在一定程度上起了作用。它删除搜索的文本,但也删除文本的结尾。

STUFF的第三个参数是从第二个参数的起始点开始要替换的字符数

SELECT
    STUFF(@main_text, 
        CHARINDEX('//', @main_text), 
        CHARINDEX('\\', @main_text) - charindex('//', @main_text) + 2, 
        '')
FROM yourTable
WHERE @main_text LIKE '%//%\\%'b

我们想删除
等等
并删除标记。从
CHARINDEX
返回的标记位置的差异是8,但我们希望删除10个字符,因此
STUFF
调用中的+2


我们可以使用
WHERE
子句来限制查询仅针对具有替换标记的记录。你可以将上面的查询放入CTE,然后更新它。

@Yogeshharma我把它搞糟了……出于某种原因,我认为
CHARINDEX
计算了字符串的结束位置,而不是开头。如果我的正文不包含斜杠和反斜杠?@I_G Wait…我明白了…只需添加一个
WHERE
子句。在我的情况下,我将使用“case”。谢谢
 text // blah \\
      6       14