TSQL - 来自URL的控制器和操作

时间:2017-05-22 19:48:00

标签: sql-server tsql url

我的应用会记录网址请求,例如:" / Users / Edit"," / News /"和" /"。
几乎所有的网址都可以通过web-api获得,它有一个" / api"在一切之前。

我需要一个

的查询
  1. 给出" / Users / Edit /"我得到了#34;用户"和"编辑" (只要结果不变,可选/
  2. 给予" /用户/"我得到了#34;用户"和NULL
  3. 给出" /"我得到NULLNULL
  4. 给出" /Content/myCss.css"我得到了内容"和(NULL或" myCss.css")
  5. 忽略" / api"
  6. 基本上,我想要的是获取控制器和该URL文本的动作......

1 个答案:

答案 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