我有一个字段,在SQL表中,用户的全名显示员工编号,然后是全名(20284 - JOAQUIM MIGUEL SAMPAIO PEREIRA)
我只想表现出“JOAQUIM PEREIRA”。
现在我正在尝试使用以下代码:
SELECT left(NMSTRING, CHARINDEX(' ',NMSTRING,CHARINDEX(' ',NMSTRING,CHARINDEX(' ',NMSTRING)+1)+1)-1) +
substring(WFPROCATTRIB.NMSTRING, len(WFPROCATTRIB.NMSTRING)-CHARINDEX(' ', REVERSE(WFPROCATTRIB.NMSTRING))+1, len(WFPROCATTRIB.NMSTRING))
FROM WHATEVER
我得到的结果是:“20284 - JOAQUIM PEREIRA”
如何删除“20284 - ”部分?
答案 0 :(得分:1)
如果员工编号总是五个字符,您只需执行以下操作:
select substring(NMString, 9, len(NMString))
另一种方法是使用charindex()
:
select substring(NMString,
charindex(' - ', NMString) + 3,
len(NMString)
)
答案 1 :(得分:1)
您可以使用子字符串来获得所需的结果
DECLARE @Name varchar(100) = '20284 - JOAQUIM PEREIRA'
SELECT SUBSTRING(@Name, CHARINDEX('-', @Name) + 1, LEN(@Name))
更多示例:
DECLARE @TestTable TABLE
(
EmployeeDetails varchar(100)
)
INSERT INTO @TestTable VALUES ('20284 - JOAQUIM PEREIRA'),
('123 - Name1') , ('12312344 - Some Other Name')
SELECT SUBSTRING(EmployeeDetails, CHARINDEX('-', EmployeeDetails) + 1, LEN(EmployeeDetails)) FROM @TestTable
答案 2 :(得分:1)
试试这个,
DECLARE @sql VARCHAR(50) = '20284 - JOAQUIM MIGUEL SAMPAIO PEREIRA'
SELECT substring(@sql, charindex('-', @sql) + 2, charindex(' ', substring(@sql, charindex('-', @sql) + 2, len(@sql)))) + ' ' + substring(@sql, LEN(@sql) - CHARINDEX(' ', REVERSE(@sql)) + 2, LEN(@sql))
答案 3 :(得分:0)
有点矫枉过正,但应该适合你:
--Declare table with example
DECLARE @WHATEVER TABLE (
NMSTRING nvarchar(max)
)
INSERT INTO @WHATEVER VALUES
(N'20284 - JOAQUIM MIGUEL SAMPAIO PEREIRA'),
(N'20285 - JOAQUIM SAMPAIO PEREIRA'),
(N'20286 - JOAQUIM PEREIRA')
--Declare xml variable
DECLARE @xml xml
--Put data in xml variable
SELECT @xml = (
SELECT CAST('<s><n>' + REPLACE(NMSTRING,' ','</n><n>') + '</n></s>' as xml)
FROM @WHATEVER
FOR XML PATH('')
)
@xml
中的数据如下所示:
<s>
<n>20284</n>
<n>-</n>
<n>JOAQUIM</n>
<n>MIGUEL</n>
<n>SAMPAIO</n>
<n>PEREIRA</n>
</s>
<s>
<n>20285</n>
<n>-</n>
<n>JOAQUIM</n>
<n>SAMPAIO</n>
<n>PEREIRA</n>
</s>
<s>
<n>20286</n>
<n>-</n>
<n>JOAQUIM</n>
<n>PEREIRA</n>
</s>
然后运行
SELECT t.v.value('n[3]','nvarchar(max)') + ' ' +
COALESCE(t.v.value('n[6]','nvarchar(max)'),t.v.value('n[5]','nvarchar(max)'),t.v.value('n[4]','nvarchar(max)'))
FROM @xml.nodes('/s') as t(v)
输出
JOAQUIM PEREIRA
JOAQUIM PEREIRA
JOAQUIM PEREIRA