在SQL Server中从字符串中搜索多个单词

时间:2014-03-20 11:23:25

标签: sql sql-server

我们将页面HTML存储在其中一个表格列中。实施例

<h3>Introducing the Targus 2014 Educational Range....</h3><span style="font-size: 12px;">Targus has launched its latest educational range. Please <a href="">click here</a> for more information. These products are now available for purchase from Dicker Data.<br><br><br>Think Outsid<img src=";fileId=38" style="float: left; width: 176px; margin: 0px 10px 10px 0px;" alt="">eOs Stowaway keyboard, distributed by Targus, is full-sized but folds to a size nearly as small as the Pocket PC itself. The keys are the same size as those on a standard keyboard, requiring little or no adjustment when using the folding keyboard. br><br> Think Outside S<img fileId=39" 

我们有一个单词“FileID”,它在该字符串中重复多次。 “FileID”始终具有分配给它的值(例如)FileID = 38,FileID = 39。

我想提取分配给此FileID的所有数字。预期输出 应该具有此字符串的结果集38和39。我尝试过下面的查询,但它只给出了第一个值。任何输入都会有所帮助。

SELECT SUBSTRING(ArtContent, CHARINDEX('fileId', mycolumn)+7,2)  from myTable

3 个答案:

答案 0 :(得分:0)

问题是您的代码仅检查第一次出现。如果你想搜索更多你需要

  • 声明一个游标。
  • 将所有ArtContent副词插入其中
  • 获取第一个并使用while循环从中获取每个fileId,直到Charindex为-1
  • 将fileId存储在temtable
  • 获取下一个重复
  • 从temptable中选择。

答案 1 :(得分:0)

试试这个脚本。

DECLARE @A TABLE (STRG VARCHAR (max)) 

INSERT INTO @A SELECT '<h3>Introducing the Targus 2014 Educational Range....</h3><span style="font-size: 12px;">Targus has launched its latest educational range. Please <a href="">click here</a> for more information. These products are now available for purchase from Dicker Data.<br><br><br>Think Outsid<img src=";fileId=38" style="float: left; width: 176px; margin: 0px 10px 10px 0px;" alt="">eOs Stowaway keyboard, distributed by Targus, is full-sized but folds to a size nearly as small as the Pocket PC itself. The keys are the same size as those on a standard keyboard, requiring little or no adjustment when using the folding keyboard. br><br> Think Outside S<img fileId=39"'

;WITH CTE(MOD_STR,STRG)

AS(

SELECT CONVERT (VARCHAR(MAX),SUBSTRING(STRG,CHARINDEX('FileID=',STRG)+7,2))
,CONVERT (VARCHAR(MAX),SUBSTRING(STRG,CHARINDEX('FileID=',STRG)+9,LEN(STRG)-CHARINDEX('FileID=',STRG))) FROM @A

UNION ALL

SELECT CONVERT (VARCHAR(MAX),MOD_STR +';'+SUBSTRING(STRG,CASE WHEN CHARINDEX('FileID=',STRG)>1 THEN CHARINDEX('FileID=',STRG)+7 ELSE LEN(STRG) END,2))
,CONVERT (VARCHAR(MAX),SUBSTRING(STRG,CASE WHEN CHARINDEX('FileID=',STRG)>1 THEN CHARINDEX('FileID=',STRG)+9 ELSE 0 END
,CASE WHEN CHARINDEX('FileID=',STRG)>1 THEN LEN(STRG)-CHARINDEX('FileID=',STRG) ELSE 0 END))

FROM CTE WHERE CHARINDEX('FileID=',STRG)>1
)

SELECT TOP 1 * FROM CTE ORDER BY LEN(STRG)ASC 

答案 2 :(得分:0)

选择--Leaddata, * 从(选择 ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS Id,[value], LEAD([value],1) OVER (ORDER BY (select 1)) LeadData FROM STRING_SPLIT(@str, ' ') ) 泰 WHERE [Value]='"key":'