删除部分文本字符串

时间:2014-07-11 18:26:43

标签: sql sql-server

SELECT  
   right(name,7),
   substring(params, charindex('|-|', params)+3,LEN(params)) as 'List Name', 
   convert(varchar,dateadd(hh,-8,created_date), 101) as Date, 
   convert(char, dateadd(hh,-8,created_date), 108) as Time 
FROM 
   [meldb].[dbo].[mr_message]
WHERE
   name in ('CL_LIST_STARTED', 'CL_LIST_STOPPED')
   AND dateadd(hh,-8,created_date) > '7/1/2014'
ORDER BY 
   created_date ASC

列表名称将返回如下内容:

firstname.lastname-|LISTNAME|-|PARENTLISTNAME

我正在尝试将LISTNAMEPARENTLISTNAME分隔成不同的列,但由于它们的字符大小不同,我不能只指定右侧或左侧

顺便说一下,我没有创建这个表,我只是坚持使用它

有什么想法吗?

3 个答案:

答案 0 :(得分:1)

您想将params分成三列吗?请查看以下查询。

SELECT  
   SUBSTRING(params, 1, CHARINDEX('-', params)-1) AS FullName,
   SUBSTRING(STUFF(params, CHARINDEX('|-|', params), LEN(params), ''), CHARINDEX('-', params) + 2, LEN(params)) AS 'List Name', 
   SUBSTRING(params, CHARINDEX('|-|', params) + 3, LEN(params)) AS 'Parent List Name', 
   CONVERT(VARCHAR,DATEADD(hh,-8,created_date), 101) AS DATE, 
   CONVERT(CHAR, DATEADD(hh,-8,created_date), 108) AS TIME 
FROM 
   [meldb].[dbo].[mr_message]
WHERE
   name IN ('CL_LIST_STARTED', 'CL_LIST_STOPPED')
   AND DATEADD(hh,-8,created_date) > '7/1/2014'
ORDER BY 
   created_date ASC

答案 1 :(得分:1)

你有没有试过呢? 好的...周五快乐:)

declare @str varchar(100);
set @str = 'jim.smith|-|firstItem|-|secondItem';



--- for your query, change @str to the column name, obviously ---
select 
    substring(
                    @str
                    , charindex('|-|', @str) + 3
                    , ( ( charindex('|-|', @str, charindex('|-|', @str) + 3) ) - ( charindex('|-|', @str) + 3) )
                )
    ,substring(
                    @str
                    , charindex('|-|', @str, charindex('|-|', @str) + 3) + 3
                    , len(@str) -- guaranteed to be past the end, to catch all
                )

答案 2 :(得分:0)

以下是我使用PAT索引和你提到的分隔符提出的格式:

SELECT name,
substring(name, 0, charindex('.', name)) as 'FirstName',
substring(name, charindex('.', name) + 1, patindex('%|-|%', name) - patindex('%-|%', name) -2) as 'LastName',
substring(name,patindex('%-|%', name)+2, patindex('%|-|%', name) - patindex('%-|%', name)-2) as 'ListName',
substring(name, patindex('%|-|%', name)+3, len(name) - patindex('%|-|%', name)) as 'ParentListName'
from FancyNames

链接到SQL小提琴:http://sqlfiddle.com/#!6/03c2c/38