2013-10-10 45 views
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但:\

+0

组合“CHARINDEX”和“SUBSTRING”调用,需要稍微调整才能使其正确。当每个部分开始或结束时,你的规则是什么?特别是在用户名后面的“仍然存在”之后 - 你怎么知道用户名已经结束,还有别的什么开始? –

+0

我说如果你知道RegEx,你甚至可以使用, –

回答

0

如果字符串是格式良好的(你总能找到令牌服务器名和用户名),你可以用PATINDEX申请得到你想要的指数,然后应用这样的SUBSTIRNG:

显示列的Sql Fiddle

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

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

完整的查询是:

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

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

'INSTR'和'CONCAT'不存在于SQL Server –

+0

@NenadZivkovic,是的更新。 – user1502952

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