我能够通过使用SubString和PatIndex来解决这个问题。谢谢大家。
解决方案:
UPDATE TableX
SET
firstname = Substring(fullname, 1, Charindex(' ', fullname) - 1),
lastname = Substring(fullname, ( Len(fullname) - Patindex(
'%[ ' + CHAR(8) + ']%',Reverse(fullname)) + 1 ) +1,Len(fullname) -
( Len(fullname) - Patindex('%[ ' + CHAR(8) + ']%',Reverse(fullname))+ 1 ))
WHERE ID = @ID
AND fullname IS NOT NULL
AND firstname = ''
原始问题:
我的分割名称功能可以分割名字和姓氏。
问题是我需要运行两次相同的功能才能获得:
有没有人有任何想法如何通过1次传递完成相同的最终结果?
UPDATE TableX
SET FirstName = dbo.ufn_SplitName(FullName,'fs'),
Lastname = dbo.ufn_SplitName(FullName,'ln')
WHERE Id = @ID AND FullName IS NOT NULL AND FirstName = ''
CREATE FUNCTION [dbo].[ufn_SplitName]
(
@pInput VARCHAR(150),
@TypeOfSplit VARCHAR(2)
)
RETURNS NVARCHAR(MAX)
AS
BEGIN
DECLARE @FINALOUTPUT AS VARCHAR(150)
DECLARE @FirstSpace as int
-- Determine the Number of spaces
SET @FirstSpace = CHARINDEX(' ',@pInput)
-- Get FirstName
if @TypeOfSplit = 'fs'
SET @FINALOUTPUT = LEFT(@pInput,@FirstSpace)
-- Last Name Does not exist so first name is the only value
if @TypeOfSplit = 'fs' AND @FirstSpace = 0
SET @FINALOUTPUT = @pInput
-- Get last Name
if @TypeOfSplit = 'ln' AND @FirstSpace > 0
SET @FINALOUTPUT = RIGHT(@pInput, CHARINDEX(' ', REVERSE(@pInput)) - 1)
-- Last Name does not exist
if @TypeOfSplit = 'ln' AND @FirstSpace = 0
SET @FINALOUTPUT = ''
return @FINALOUTPUT
答案 0 :(得分:2)
如果不深入了解代码的细节,可以将其更改为表值函数,该函数返回一行,其中包含每个名字和姓氏的列。然后,您可以JOIN
查询查询中的表值函数,并在查询中使用这些列。
答案 1 :(得分:0)