I have a varchar column which contains something like this:
(0 or more lines of random text)
Name: John Doe
(0 or more another lines...)
I need a select query that gives me just „John Doe”. Any ideas?
In other words: I look for SQL equivalent of: grep ”^Name:”|sed -es/^Name://
Assuming the lines are carriage returns which is 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.
this will work:
select * from tablename where regexp_like(colname,'^(Name)(.*)$');
sql server equivalent:
select substr(colname,CHARINDEX('Name ',colname)+5,8) from tablename where
PATINDEX(colname,'^(Name)(.*)$');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.