让我们考虑一下表格下方。
输入表
Emp_ID EmployeeName
1 Mark hos
2 jhon carte
3 Mike hold
4 Mark Danny
5 Stacy hodegf
如何检索如下所示的输出
Output Table
Mark
jhon
Mike
Mark
Stacy
答案 0 :(得分:2)
您可以将Left
与CharIndex
一起使用:
首先,创建并填充示例表(请在您将来的问题中为我们保存此步骤)
DECLARE @T AS TABLE
(
Emp_ID int,
EmployeeName varchar(20)
)
INSERT INTO @T (Emp_Id, EmployeeName ) VALUES
(1, 'Mark hos'),
(2, 'jhon carte'),
(3, 'Mike hold'),
(4, 'Mark Danny'),
(5, 'Stacy hodegf'),
(6, 'NoSpaceHere')
查询:
SELECT Emp_Id, LEFT(EmployeeName, CHARINDEX(' ', EmployeeName +' ')) As FirstName
FROM @T
结果:
Emp_Id FirstName
1 Mark
2 jhon
3 Mike
4 Mark
5 Stacy
6 NoSpaceHere
请注意,我在EmployeeName
函数中的charindex
处添加了尾随空格,以在没有空格的情况下返回整个EmployeeName
。
答案 1 :(得分:0)
您可以尝试使用substring()和charindex()函数
Q_GLOBAL_STATIC(ServiceManager, myServiceManagerInstance)
ServiceManager *ServiceManager::instance()
{
return myServiceManagerInstance();
}
答案 2 :(得分:0)
您可以使用SUBSTRING,CHARINDEX作为其他答案,也可以看看STRING_SPLIT,这可能是一个更好的解决方案:
https://docs.microsoft.com/en-us/sql/t-sql/functions/string-split-transact-sql?view=sql-server-2017
答案 3 :(得分:0)
CREATE TABLE #TempEmp
(
Emp_ID INT,
EmployeeName VARCHAR(100)
)
INSERT INTO #TempEmp
SELECT 1,'Mark hos' UNION
SELECT 2,'jhon carte' UNION
SELECT 3,'Mike hold' UNION
SELECT 4,'Mark Danny' UNION
SELECT 5,'Stacy hodegf'
SELECT
SUBSTRING(EmployeeName, 1, CASE WHEN CHARINDEX(' ', EmployeeName)>0 THEN CHARINDEX(' ', EmployeeName) - 1 ELSE LEN(EmployeeName) END ) AS Firstname FROM #TempEmp