1

我有以下不同类型的输入nvarchar值:

  • FirstName|LastName
  • FirstName
  • |LastName

我需要在我的 SQL 脚本中输出FirstNameLastName作为单独的列。

SELECT FLname as Original
    ,SUBSTRING(FLname, 0, ISNULL(NULLIF(CHARINDEX('|', FLname),0), LEN(FLname)+1)) as FirstName
    ,SUBSTRING(FLname, ISNULL(NULLIF(CHARINDEX('|', FLname)+1,1), LEN(FLname)+1), LEN(FLname)+1) as LastName

这个逻辑确实有效,但我觉得它不可读,特别是对于未来的开发人员来说。

我知道我可以创建一个用户定义的函数来存储这个逻辑,但我宁愿避免添加这个。

作为内联 SQL 语句,是否有更简洁的方法来实现所需的结果?

4

2 回答 2

0

这与@RBarryYoung 的答案非常相似,CTE为了清晰易读,使用CHARINDEX,LEFTRIGHT函数。如果需要,您可以将空字符串 ( '') 替换为 null。

小提琴演示

;with cte as (
  select FLname, charindex('|',FLname) divider
  from t
)
select FLname original, 
       case when divider = 1 then ''
            when divider > 1 then left(FLname, divider-1) 
       else FLname end firstName,
       case when divider > 0 then right(FLname, len(FLname)-divider)
            else '' end lastName
from cte

|           ORIGINAL | FIRSTNAME | LASTNAME |
---------------------------------------------
| FirstName|LastName | FirstName | LastName |
|          FirstName | FirstName |          |
|          |LastName |           | LastName |
于 2013-04-29T14:29:18.733 回答
0

我会这样做:(已更正)

;WITH cte As
(
    SELECT *,CHARINDEX('|', FLname) As PipeOffset
    FROM yourTable
)
SELECT
    FLname As Original,
    CASE When PipeOffset = 0 Then FLname
         When PipeOffset > 1 Then LEFT(FLname, PipeOffset-1)
         ELSE NULL  END     As FirstName,
    CASE When >0 And < LEN(FLname) 
         Then RIGHT(FLname, LEN(FLname)- PipeOffset)
         ELSE NULL  END     As LastName
FROM cte
于 2013-04-29T14:24:44.393 回答