如何只获取表格中的中间部分?我尝试了以下代码,但这只删除了正确的部分...我的输出应该只是中间部分。
例如,当我选择数据1-021514-1
时,输出应该是021514
,而不是左右虚线
select LEFT(ticketid, CHARINDEX('-', ticketid + '-') + 4)
from Table
我的数据是:
|TicketID |
------------
|1-021514-1 |
|10-021514-1|
|2-021514-1 |
|4-021414-1 |
答案 0 :(得分:2)
请尝试:
SELECT
LEFT(st, CHARINDEX('-', st)-1) TicketID
from
(
SELECT
SUBSTRING(TicketID, CHARINDEX('-',TicketID)+1, 10000) st
FROM Table
)x
答案 1 :(得分:1)
试试这个
with t as (select TicketID as val)
select t.*,
LEFT(val, charindex('-', val) - 1),
SUBSTRING(val, charindex('-', val)+1, len(val) - CHARINDEX('-', reverse(val)) - charindex('-', val)),
REVERSE(LEFT(reverse(val), charindex('-', reverse(val)) - 1))
from t;
(OR)
使用以下功能
CREATE FUNCTION dbo.SplitStrings_CTE(@List nvarchar(max), @Delimiter nvarchar(1))
RETURNS @returns TABLE(val nvarchar(max), [level] int, PRIMARY KEY CLUSTERED([level]))
AS
BEGIN
;WITH cte AS
(
SELECT SUBSTRING(@List, 0, CHARINDEX(@Delimiter, @List)) AS val,
CAST(STUFF (@List + @Delimiter, 1, CHARINDEX(@Delimiter, @List), '') AS nvarchar(max)) AS stval,
1 AS [level]
UNION ALL
SELECT SUBSTRING(stval, 0, CHARINDEX(@Delimiter, stval)),
CAST(STUFF (stval, 1, CHARINDEX(@Delimiter, stval), '') AS nvarchar(max)),
[level] + 1
FROM cte
WHERE stval != ''
)
INSERT @returns
SELECT REPLACE(val, ' ', '') AS val, [level]
FROM cte
RETURN
END
答案 2 :(得分:1)
嗨罗恩试试这个,
declare @string varchar(25)='1-021514-1'
declare @val varchar(25)
SELECT @val= SUBSTRING(@string, CHARINDEX('-', @string)+1, ((CHARINDEX('-',@string,(charindex('-',@string)+1))-CHARINDEX('-', @string))-1))
select @val
答案 3 :(得分:0)
试试这个:
select right(left(ticketid, charindex('-', ticketid, charindex('-', ticketid, 0) + 1) - 1), len(left(ticketid, charindex('-', ticketid, charindex('-', ticketid, 0) + 1) - 1)) - charindex('-', left(ticketid, charindex('-', ticketid, charindex('-', ticketid, 0) + 1) - 1), 0)) from Table
答案 4 :(得分:0)
试试这个
SELECT STUFF(
STUFF(TicketID,1,CHARINDEX('-',TicketID,1),'')
,CHARINDEX('-',STUFF(TicketID,1,CHARINDEX('-',TicketID,1),''),1)
,LEN(TicketID)
,'')
from Table1