我有一个varchar列,其中包含以下内容:
(0行或多行随机文本)
名称:John Doe
(0行或更多行...)
我需要一个选择查询,仅给我“ John Doe”。有什么想法吗?
换句话说:我在寻找SQL等效项: grep” ^ Name:” | sed -e s / ^ Name://
答案 0 :(得分:1)
假设这些行是回车符,即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
使用案例
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
如果还有其他内容,例如换行符(ASCII 10),则只需相应地调整char(##)。
答案 1 :(得分:0)
这将起作用:
select * from tablename where regexp_like(colname,'^(Name)(.*)$');
等效的SQL Server:
select substr(colname,CHARINDEX('Name ',colname)+5,8) from tablename where
PATINDEX(colname,'^(Name)(.*)$');