字符串操作/正则表达式

时间:2020-04-30 17:57:36

标签: sql sql-server

我有一个NVARCHAR(MAX)列,用于存储日志流。我需要在select语句级别提取一些值。由于没有CLR我无法应用正则表达式,使用某些“字符串操作”函数的解决方案是什么?

例如,我可能在Log列中具有以下值:

$CF_NONPROD_USERNAME -p $CF_NONPROD_PASSWORD -o $ORG -s $SPACE\u001B[0;m\nAPI endpoint: https://api.server02.pcf.com/\nAuthenticating...\nOK\n\nTargeted org Order-PSOrg\n\nTargeted space TEST4\n\n\n\nAPI endpoint:   https://api.server02.pcf.com (API version: 2.131.0)\nUser:           myuser@user.from.ldap.cf\nOrg:            Order-PSOrg\nSpace:          TEST4\n\u001B[32;1m$ $PRE_DEPLOY_CMD\u001B[0;m\n\"Deployment started\"\n\u001B[32;1m$ cf push $APP_NAME -p $TARGET -f $PCF_MF_FILE --no-start\u001B[0;m\nPushing f

我需要提取:

Targeted Org = *in this sample would be "Order-PSOrg"*

Targeted Space = *in this sample would be "TEST4"*

Api Endpoint = *in this sample would be "https://api.server02.pcf.com"*

有什么建议吗?

谢谢

1 个答案:

答案 0 :(得分:0)

此查询非常丑陋,但可以完成工作。基本上,您从要查找的键的位置(“ Targeted Org”,“ Targeted Space”和“ Api Endpoint”)中检索子字符串,直到下一个“ \ n”字符串的位置为止。最后,您从先前的结果中删除了该密钥。

使用的功能:

  1. 字符索引以获取子字符串在字符串中的位置
  2. 子字符串以在两个位置之间获取子字符串
  3. 替换以从上一个结果中删除搜索到的关键字
  4. ltrim rtrim 删除开头和结尾的空格

查询:

create table MyLogsTable (Log varchar(max))    
insert into MyLogsTable (Log) values ('$CF_NONPROD_USERNAME -p $CF_NONPROD_PASSWORD -o $ORG -s $SPACE\u001B[0;m\nAPI endpoint: https://api.server02.pcf.com/\nAuthenticating...\nOK\n\nTargeted org Order-PSOrg\n\nTargeted space TEST4\n\n\n\nAPI endpoint: https://api.server02.pcf.com (API version: 2.131.0)\nUser: myuser@user.from.ldap.cf\nOrg: Order-PSOrg\nSpace: TEST4\n\u001B[32;1m$ $PRE_DEPLOY_CMD\u001B[0;m\n\"Deployment started\"\n\u001B[32;1m$ cf push $APP_NAME -p $TARGET -f $PCF_MF_FILE --no-start\u001B[0;m\nPushing f')

select ltrim(rtrim(replace(substring(Log, charindex('Targeted Org', Log), charindex('\n', Log, charindex('Targeted Org', Log)) - charindex('Targeted Org', Log)), 'Targeted Org', ''))) as Target_Org,
       ltrim(rtrim(replace(substring(Log, charindex('Targeted Space', Log), charindex('\n', Log, charindex('Targeted Space', Log)) - charindex('Targeted Space', Log)), 'Targeted Space', ''))) as Target_Space,
       ltrim(rtrim(replace(substring(Log, charindex('Api Endpoint:', Log), charindex('\n', Log, charindex('Api Endpoint:', Log)) - charindex('Api Endpoint:', Log)), 'Api Endpoint:', ''))) as Api_Endpoint       
from MyLogsTable       

You can see it working at DBFiddle