简体   繁体   English

Microsoft SQL Server:如何从多行字段中提取数据?

[英]Microsoft SQL Server: How to extract data from multiline field?

I have a varchar column which contains something like this: 我有一个varchar列,其中包含以下内容:

(0 or more lines of random text) (0行或多行随机文本)

Name: John Doe 姓名:约翰·杜

(0 or more another lines...) (0或更多其他行...)

I need a select query that gives me just „John Doe”. 我需要一个选择查询,仅给我“ John Doe”。 Any ideas? 有任何想法吗?

In other words: I look for SQL equivalent of: grep ”^Name:”|sed -es/^Name:// 换句话说:我在寻找SQL等效项:grep” ^ Name:” | sed -es / ^ Name://

Assuming the lines are carriage returns which is ASCII 13: 假设这些行是回车符,即ASCII 13:

declare @table table (c varchar(max))

insert into @table
values
('adsfsdfdsa' + char(13) + 'Name: John Doe' + char(13) + 'adsfdsafasd'),
('Name: John Doe' + char(13) + 'adsfdsafasd'),
('adsfsdfdsa' + char(13) + 'Name: John Doe'),
('Name: John Doe')

select *
    ,WithAttribute = substring(c,charindex('Name:',c),iif(charindex(char(13),substring(c,charindex('Name:',c),99)) = 0,99,charindex(char(13),substring(c,charindex('Name:',c),99))))
    ,OnlyName = substring(
                        substring(c,charindex('Name:',c),iif(charindex(char(13),substring(c,charindex('Name:',c),99)) = 0,99,charindex(char(13),substring(c,charindex('Name:',c),99))))
                        ,6,99)
from @table

USING CASE 使用案例

select *
    ,WithAttribute = substring(c,charindex('Name:',c),case when charindex(char(13),substring(c,charindex('Name:',c),99)) = 0 then 99 else charindex(char(13),substring(c,charindex('Name:',c),99)) end )
    ,OnlyName = substring(
                        substring(c,charindex('Name:',c),case when charindex(char(13),substring(c,charindex('Name:',c),99)) = 0 then 99 else charindex(char(13),substring(c,charindex('Name:',c),99)) end )
                        ,6,99)
from @table

If they are something else, like line feed (ASCII 10) then just adjust the char(##) accordingly. 如果还有其他问题,例如换行(ASCII 10),则只需相应地调整char(##)。

this will work: 这将工作:

select * from tablename where regexp_like(colname,'^(Name)(.*)$');

sql server equivalent: 等效的sql server:

select substr(colname,CHARINDEX('Name ',colname)+5,8) from tablename where  
PATINDEX(colname,'^(Name)(.*)$');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM