我试图连接一些球员没有中间名的球员的名字。在连接如下时,我为没有中间名的玩家获得了一个空白区域,并且逻辑适用于具有中间名的玩家。如何仅为NULL值列删除不需要的空格?
我只想在concatenate表达式中使用中间名的Initial。
SELECT m_playerid, first_name + ' ' + SUBSTRING (coalesce (middle_
name, ' '), 1,1) + ' ' + last_name as [Full name]
, game as Game, inns as Innings, [scores] as Scores FROM odsports
我不应该引入条件来删除 空格为NULL?我很震惊!
答案 0 :(得分:3)
您可以使用NULL
与+
运算符连接的任何内容生成NULL
这一事实,而CONCAT
函数将NULL
转换为空字符串
所以CONCAT(first_name, ' ', LEFT(middle_name,1) + ' ', last_name)
将根据需要处理空中间名 - 如下例
WITH T(first_name, middle_name, last_name) AS
(
SELECT 'Franklin', 'Delano', 'Roosevelt' union all
SELECT 'Barack', NULL, 'Obama'
)
SELECT CONCAT(first_name, ' ', LEFT(middle_name,1) + ' ', last_name)
FROM T
返回
+----------------------+
| (No column name) |
+----------------------+
| Franklin D Roosevelt |
| Barack Obama |
+----------------------+
答案 1 :(得分:1)
为双空格添加替换,以及使用isnull函数。试试这个
SELECT
m_playerid,
REPLACE(
LTRIM(RTRIM(ISNULL(first_name ,'')))
+CASE WHEN middle_name IS NULL
THEN ' '
ELSE ' '+LEFT(ISNULL(middle_name,' '),1)+' ' END
+
LTRIM(RTRIM(ISNULL(last_name,'')))
,' ',' ') as [Full name],
game as Game,
inns as Innings,
[scores] as Scores
FROM odsports
答案 2 :(得分:0)
试试这个:
SELECT m_playerid,
COALESCE(first_name + ' ' + middle_name + ' ' + last_name,
first_name + ' ' + last_name,
first_name,
last_name) as [Full name],
game as Game,
inns as Innings,
[scores] as Scores
FROM odsports
答案 3 :(得分:0)
SELECT
m_playerid,
LTRIM(CONCAT(first_name,Space(1),LTRIM(RTRIM(middle_name+space(1)+last_name))))
as [Full name],
game as Game,
inns as Innings,
[scores] as Scores
FROM odsports