创建视图。用空字符串替换NULL值。 SQL

时间:2017-01-24 08:48:39

标签: sql sql-server view

我想从一个表中创建一个视图,其中我们有一个FirstName,LastName和MiddleName列,其中MiddleName可能是NULL,加上一个工资。我需要将MiddleName替换为空字符串,而不是MiddleName。我正在使用SQL Management Studio。 我想出了这段代码:

CREATE VIEW V_EmployeeNameJobTitle AS
SELECT FirstName  + ' ' + MiddleName + ' ' + LastName AS [Fullname], Salary FROM Employees WHERE MiddleName IS NOT NULL
UNION SELECT FirstName  + ' ' + LastName AS [Fullname], Salary FROM Employees WHERE MiddleName IS NULL 

但这似乎并不像我想的那样有效,并且它不是很漂亮。任何其他建议我如何缩短这个。提前谢谢。

3 个答案:

答案 0 :(得分:2)

SELECT FirstName + ' ' + 
       (case when MiddleName is null then '' else MiddleName + ' ' end) +
       LastName AS [Fullname]

答案 1 :(得分:1)

使用ISNULL()函数,它将NULL值替换为您选择的值。例如:

CREATE VIEW V_EmployeeNameJobTitle AS
SELECT FirstName  + ' ' + ISNULL(MiddleName, '') + ' ' + LastName AS [Fullname], Salary 
FROM Employees 

如果您不希望在中间名为空时获得2个空格,则可以执行以下操作:

CREATE VIEW V_EmployeeNameJobTitle AS
SELECT (CASE WHEN MiddleName IS NULL THEN FirstName  + ' ' + LastName
             ELSE FirstName  + ' ' + MiddleName + ' ' + LastName END) AS [Fullname], 
Salary 
FROM Employees 

答案 2 :(得分:0)

使用IsNull功能

 CREATE VIEW V_EmployeeNameJobTitle AS
    SELECT FirstName  + ' ' 
         + MiddleName + ' ' 
         + IsNull(LastName, '') AS [Fullname]
   , Salary 
 FROM Employees