我的select语句返回两列A列基于B列但是我删除了最初的17个字符。我想要做的是将A列中的所有字符都取出,直到它达到\(反斜杠)。任何人都可以帮助我实现这一目标 - 下面的当前代码
SELECT distinct substring(Path,17,18) AS Detail, Path
FROM [DB].[dbo].[Projects]
Where [Path] like '\DATA%'
AND [Deleted] = '0'
重新迭代,因为我的例子在下面的评论中不是很清楚。我试图从以下结果中提取
\DATA\More Data\Even More Data\Data 1
显示
Even More Data
所以我删除了前17个字符,直到下一个\
答案 0 :(得分:1)
对于ColumnA,如果您只想取出前17个字符,则应使用
RIGHT(Path, LEN(Path) - 17)
如果Path超过35个字符,则当前解决方案将无法正常工作。
至于将字符串返回到第一个反斜杠,请使用:
SELECT LEFT(Detail, CHARINDEX('\', Detail)) FirstFolder, Detail, Path
FROM
(
SELECT distinct RIGHT(Path, LEN(Path) - 17) AS Detail, Path
FROM [DB].[dbo].[Projects]
Where [Path] like '\DATA%'
AND [Deleted] = '0'
) a
或者一体化:
SELECT DISTINCT SUBSTRING(Path, 18, CHARINDEX('\', Path, 18) - 18)
FROM [DB].[dbo].[Projects]
WHERE [Path] like '\DATA%'
AND [Deleted] = '0'
这说:
path
path
中第一个反斜杠的位置来计算(因为我们开始搜索第18个字符,我们希望它相对于我们的搜索开始不原始字符串的开头)<强>更新强>
正如@etsa正确指出的那样,如果你不能保证Path长度至少为18个字符并且在每行 之后包含一个反斜杠 ,你应该使用以下内容仅返回符合此条件的行:
SELECT DISTINCT SUBSTRING(Path, 18, CHARINDEX('\', Path, 18) - 18)
FROM [DB].[dbo].[Projects]
WHERE [Path] like '\DATA%'
AND [Deleted] = '0'
AND CHARINDEX('\', Path, 18) > 0
答案 1 :(得分:0)
无论数据的长度如何,这都会获得您想要的父文件夹。
DECLARE @table TABLE ([Path] VARCHAR(256))
INSERT INTO @table VALUES
('\DATA\More Data\Even More Data\Data 1'),
('\\server\top folder\middle folder\bottom folder\file 1'),
('x\x\x\x\x\x\x\x\x\x\x\x\x\x\x\x\x\x\x\this is what we want\x')
SELECT
[Path]
,CHARINDEX('\',REVERSE([Path])) as [Reverse Position of last \]
,CHARINDEX('\',REVERSE([Path]),CHARINDEX('\',REVERSE([Path])) + 1) as [Reverse Postion of next to last \]
,REVERSE(
SUBSTRING(
REVERSE([Path]),
CHARINDEX('\',REVERSE([Path]))+1,
CHARINDEX('\',REVERSE([Path]),CHARINDEX('\',reverse([Path]))+1)-CHARINDEX('\',REVERSE([Path])) - 1)) as [Your Desired Results]
FROM
@table
<强>返回强>
+--------------------------------------------------------------+----------------------------+-----------------------------------+----------------------+
| Path | Reverse Position of last \ | Reverse Postion of next to last \ | Your Desired Results |
+--------------------------------------------------------------+----------------------------+-----------------------------------+----------------------+
| \DATA\More Data\Even More Data\Data 1 | 7 | 22 | Even More Data |
| \\server\top folder\middle folder\bottom folder\file 1 | 7 | 21 | bottom folder |
| x\x\x\x\x\x\x\x\x\x\x\x\x\x\x\x\x\x\x\this is what we want\x | 2 | 23 | this is what we want |
+--------------------------------------------------------------+----------------------------+-----------------------------------+----------------------+