我的应用会记录网址请求,例如:" / Users / Edit"," / News /"和" /"。
几乎所有的网址都可以通过web-api获得,它有一个" / api"在一切之前。
我需要一个
的查询/
)NULL
NULL
和NULL
NULL
或" myCss.css")基本上,我想要的是获取控制器和该URL文本的动作......
答案 0 :(得分:1)
你几乎完成了它。尝试一下xml。
-- Sample data.
declare @URLs as Table ( URL VarChar(256), Controller VarChar(256), [Action] VarChar(256) );
insert into @URLs ( URL ) values
( '/Users/Edit/' ),
( '/Users/' ),
( '/' ),
( '/Content/myCss.css' ),
( '/api/Users/Edit/' ),
( '/api/Users/' ),
( '/api/' ),
( '/api/Content/myCss.css' );
select * from @URLs;
-- Flog it into submission.
select URL, XMLURL, Ele2, Ele3, Ele4, Leonard.Controller, Leonard.[Action]
from @URLs as U cross apply
( select Cast( '<root><ele>' + Replace( URL, '/', '</ele><ele>' ) + '</ele></root>' as XML ) as XMLURL ) as XU cross apply
( select XMLURL.value('(/root/ele)[2]', 'varchar(256)') as Ele2,
XMLURL.value('(/root/ele)[3]', 'varchar(256)') as Ele3,
XMLURL.value('(/root/ele)[4]', 'varchar(256)') as Ele4 ) as XE cross apply
( select NullIf( case when Ele2 = 'api' then Ele3 else Ele2 end, '' ) as Controller,
NullIf( case when Ele2 = 'api' then Ele4 else Ele3 end, '' ) as [Action] ) as Leonard;
-- Update the table.
update U
set Controller = Leonard.Controller, [Action] = Leonard.[Action]
from @URLs as U cross apply
( select Cast( '<root><ele>' + Replace( URL, '/', '</ele><ele>' ) + '</ele></root>' as XML ) as XMLURL ) as XU cross apply
( select XMLURL.value('(/root/ele)[2]', 'varchar(256)') as Ele2,
XMLURL.value('(/root/ele)[3]', 'varchar(256)') as Ele3,
XMLURL.value('(/root/ele)[4]', 'varchar(256)') as Ele4 ) as XE cross apply
( select NullIf( case when Ele2 = 'api' then Ele3 else Ele2 end, '' ) as Controller,
NullIf( case when Ele2 = 'api' then Ele4 else Ele3 end, '' ) as [Action] ) as Leonard;
select * from @URLs;
这个概念是将每个URL转换为XML,路径上的每个元素都是一个单独的XML元素。由于可以使用XML.value
通过索引访问元素,因此很容易选择前几个元素,使用'api'
忽略case
,并使用{{1将任何空字符串转换为空值}}
对于那些只了解T-SQL辩证法的人,要求每行以非数字非字母字符开头,提供了初始示例的大写翻译:
NullIf