1

我不是数据库管理员,但我经常需要查询数据库来完成我的工作。最近,我的任务是查询数据库列中以分号分隔的表达式的长度。显示为虚构的示例表和列可能会更容易:

  • 表是Table1
  • 列是Column1

中两行的值Table1.Column1如下所示:

principal_name='Joe Schmoe'; marital_status='m'; shoe_size='12.5';
message='This is a message which is 45 characters long'; 
years_active='15'

principal_name='Jim Schmim'; marital_status='s'; shoe_size='10.5'; 
message='This is a xxxxxxxxxxx message which is 57 characters long'; 
years_active='6' 

我需要查询Table1.Column1并找出该列的消息部分中有多少行超过 50 个字符。

如果该列只有一个值,我可以使用类似的东西:

SELECT COUNT(*) FROM Table1 WHERE LEN(column1) > 40

但是,我不需要知道该字段总共有多少个字符,只需要知道message=和之间有多少个;

我以前从来没有处理过一个有多个值用分号分隔的列,所以我不知道如何查询我需要知道的内容。

4

3 回答 3

1

假设 column1 中总是有相同的部分,以相同的顺序,例如
where ( CharIndex('years_active=',column1) - CharIndex('message=',column1) ) >50
(对描述的长度进行一些调整等)

于 2013-03-08T21:08:16.353 回答
0

您可以在自定义函数中尝试这样的事情

Declare @str varchar(max);
set @str = 'aaaabc=thisisatest;aaaaa'
select LEN(substring(@str,CHARINDEX('=',@str,0)+1, CHARINDEX(';',@str,0)-CHARINDEX('=',@str,0)-1))
于 2013-03-08T21:05:44.980 回答
0

尝试这个

;with cte as
(
    select 'principal_name=''Joe Schmoe''; marital_status=''m''; shoe_size=''12.5'';message=''This is a message which is 45 characters long'';years_active=''15''' as column1
    union
    select 'principal_name=''Jim Schmim''; marital_status=''s''; shoe_size=''10.5''; message=''This is a xxxxxxxxxxx message which is 57 characters long''; years_active=''6'''
), 
cte2 as 
(
    SELECT ltrim(rtrim(r.value('.','VARCHAR(MAX)'))) as Item from (
    select CONVERT(XML, N'<root><r>' + REPLACE(column1,';','</r><r>') + '</r></root>') as XmlString
    from cte ) x
    CROSS APPLY x.XmlString.nodes('//root/r') AS RECORDS(r)
)
--SELECT *, LEN(item) - 10 from cte2 x where x.Item like 'message=%' and LEN(item) > 50
SELECT COUNT(*) cnt from cte2 x where x.Item like 'message=%' and LEN(item) > 50
于 2013-03-08T21:21:30.950 回答