0

我在 SQL Server 表中有大字符串。

示例一记录表行:

06.10.2013 22:49:25 [Server Name] INFO - received /192.168.77.14:45643 User-Name: Jon Johnson still something between Client IP: 172.29.5.43

但我只需要:

06.10.2013 22:49:25 User-Name: Jon Johnson Client IP: 172.29.5.43

我该怎么做?我尝试使用 PATINDEX 但是:\

4

4 回答 4

1
SELECT 
LEFT(c, 19) -- fixed length for date-time
+ ' ' -- separator
-- now let's find the user-name.
+ SUBSTRING(c, CHARINDEX('User-Name:',c), CHARINDEX(' still something',c ) - CHARINDEX('User-Name:',c)) -- 'User-name:' string must be present only once in the row-column. Replace ' still something' string with the actual content. You use it to delimit the username itself.
+ ' ' -- separator
+ SUBSTRING(c, CHARINDEX('Client IP:',c) /* first character position to include */, LEN(c) - CHARINDEX('Client IP:',c) + 1 /* last character position not to include */) -- 'Client IP:' string must be resent only once in the row-column. Expects the IP to be the last part of the string, otherwise use the technique from the username

-- now the dummy table for the testing
FROM 
(SELECT '06.10.2013 22:49:25 [Server Name] INFO - received /192.168.77.14:45643 User-Name: Jon Johnson still something between Client IP: 172.29.5.43' AS c) AS t
于 2013-10-10T07:59:32.807 回答
0

列的日期部分是固定的,因此可以使用SUBSTRING函数提取固定长度。

完整的查询是:

SELECT SUBSTRING(fieldname,1,20) + SUBSTRING(fieldname, CHARINDEX('User-Name', 

fieldname), LENGTH(fieldname)-CHARINDEX('User-Name', fieldname)) from table;  
于 2013-10-10T07:57:56.403 回答
0

如果您的字符串格式正确(您总是可以找到令牌服务器名称和用户名),您可以使用 PATINDEX 申请以获取您想要的索引,然后像这样应用 SUBSTIRNG:

显示Sql 小提琴

select
substring(description, 1, patindex('%Server Name%', description) - 3) +
substring(description, patindex('%User-name%', description) + 9, 500)
from myTable
于 2013-10-10T07:49:32.700 回答
0

这可能会起作用,但是您确实需要用更可靠的东西替换“仍然介于两者之间”的东西:

DECLARE @s NVARCHAR(MAX)
SET @s = '06.10.2013 22:49:25 [Server Name] INFO - received /192.168.77.14:45643 User-Name: Jon Johnson still something between Client IP: 172.29.5.43'


SELECT SUBSTRING(@s,0,CHARINDEX('[Server Name]',@s)) --everything up to [Server Name]
   + SUBSTRING(@s, CHARINDEX('User-Name',@s),CHARINDEX('still something between', @s)-CHARINDEX('User-Name',@s)) --everything from User-Name to 'still something between'
   + SUBSTRING(@s, CHARINDEX('Client IP',@s),LEN(@s)) --from Client IP till the end
于 2013-10-10T08:00:18.790 回答