我想从列中的字符串中获取服务器名称 前
CREATE TABLE #Sample(ServerPath varchar(50))
GO
INSERT INTO #Sample (ServerPath) VALUES ('\\TestServer1\Test')
INSERT INTO #Sample (ServerPath) VALUES ('\\TestServer2\Test')
INSERT INTO #Sample (ServerPath) VALUES ('\\TestServer3\Test')
INSERT INTO #Sample (ServerPath) VALUES ('TestServer4)
SELECT * FROM #Sample
GO
DROP TABLE #Sample`enter code here`
我希望在双斜杠到第一个单斜杠之间输出类似字符串
TestServer1
TestServer2
TestServer3
在sql中执行什么sql命令或正则表达式给出了我预期的结果。
答案 0 :(得分:1)
这不需要是正则表达式(根据您的标记)。只需使用这样的东西。
CREATE TABLE #Sample(ServerPath varchar(50))
INSERT INTO #Sample (ServerPath)
VALUES
('\\TestServer1\Test')
,('\\TestServer2\Test')
,('\\TestServer3\Test')
SELECT
SUBSTRING(ServerPath,3,CHARINDEX('\',ServerPath,3)-3) Result
FROM #Sample
Result
TestServer1
TestServer2
TestServer3
这假设它始终以双反斜杠
开头如果你有没有反斜杠的数据,那么先用它来检查;
CREATE TABLE #Sample(ServerPath varchar(50))
INSERT INTO #Sample (ServerPath)
VALUES
('\\TestServer1\Test')
,('\\TestServer2\Test')
,('\\TestServer3\Test')
,('TestServer4')
SELECT
CASE
WHEN CHARINDEX('\\',ServerPath) = 0
THEN ServerPath
ELSE SUBSTRING(ServerPath,3,CHARINDEX('\',ServerPath,3)-3)
END Result
FROM #Sample
GO
DROP TABLE #Sample
Result
TestServer1
TestServer2
TestServer3
TestServer4