簡體   English   中英

Microsoft SQL Server:如何從多行字段中提取數據?

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

我有一個varchar列,其中包含以下內容:

(0行或多行隨機文本)

姓名:約翰·杜

(0或更多其他行...)

我需要一個選擇查詢,僅給我“ John Doe”。 有任何想法嗎?

換句話說:我在尋找SQL等效項:grep” ^ Name:” | sed -es / ^ Name://

假設這些行是回車符,即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(##)。

這將工作:

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

等效的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