按图案切割字符串

时间:2013-10-10 07:36:31

标签: sql sql-server

我在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 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

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

显示Sql Fiddle

select
substring(description, 1, patindex('%Server Name%', description) - 3) +
substring(description, patindex('%User-name%', description) + 9, 500)
from myTable

答案 2 :(得分:0)

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

完整查询是:

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

fieldname), LENGTH(fieldname)-CHARINDEX('User-Name', fieldname)) from table;  

答案 3 :(得分: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