我的查询需要一些帮助。我是子查询的新手。我想替换表中的每一行,在姓氏列中没有姓氏的空值,并输出所有没有姓氏的值。我收到一个错误,我不知道如何解决这个问题。将不胜感激任何帮助。
SELECT
Firstname,
ISNULL(dbo.Mechanics.LastName, 'No lastname') AS Lastname
FROM
dbo.Mechanics
WHERE
Lastname = (SELECT FirstName, Lastname
FROM Mechanics
WHERE LastName = 'No lastname');
我收到了这个错误:
Msg 116,Level 16,State 1,Line 4
引入子查询时,只能在选择列表中指定一个表达式
当未使用EXISTS
答案 0 :(得分:1)
不确定此处是否需要子查询。试试这个:
SELECT
Firstname, 'No Lastname' AS Lastname
FROM Dbo.Mechanics
WHERE Lastname IS NULL ;
答案 1 :(得分:1)
SELECT m.Firstname ,
ISNULL(m.LastName, 'No lastname') AS Lastname
FROM dbo.Mechanics M
WHERE EXISTS ( SELECT 1
FROM Mechanics M1
WHERE m1.LastName = 'No lastname'
AND m.LastName = m1.LastName )
答案 2 :(得分:0)
我看不出子查询与此有什么关系。这应该足够了:
SELECT m.Firstname, COALESCE(m.LastName, 'No lastname') AS Lastname
FROM Dbo.Mechanics m
WHERE m.Lastname IS NULL;
您还应该学习如何使用表别名,这样您的查询就更容易编写和阅读。
答案 3 :(得分:0)
我想替换表中没有姓氏
的姓氏列中包含空值的每一行
这是通过UPDATE Dbo.Mechanics SET LastName = 'No lastname' WHERE LastName IS NULL
声明完成的:
SELECT FirstName, LastName FROM Dbo.Mechanics WHERE LastName = 'No lastname'
并输出所有没有姓氏的值
然后,选择很简单:
{{1}}
答案 4 :(得分:0)
你没有两个写任何子查询,因为你可以首先更新表IS NULL列
UPDATE dbo.Mechanics SET LastName ='No Lastname' WHERE LastName IS NULL
然后将SELECT语句与WHERE子句一起使用,使LastName等于' No Lastname'
SELECT FirstName,LastName FROM dbo.Mechanics WHERE LastName = 'No Lastname'
编辑:
根据您的评论,您不希望永久更新LastName列,而不是使用COALESCE
SELECT FirstName,COALESCE(LastName, 'No lastname') AS LastName FROM dbo.Mechanics WHERE LastName IS NULL
答案 5 :(得分:0)
如果您想要UPDATE表数据并查看更新的记录您可以使用OUTPUT子句输出查询结果: https://docs.microsoft.com/en-us/sql/t-sql/queries/output-clause-transact-sql
查询shuld:
UPDATE Mechanics
SET LastName = 'No lastname'
FROM Mechanics WHERE LastName IS NULL
OUTPUT inserted.*
如果您要选择具有更正姓氏的所有数据:
SELECT FirstName, ISNULL(LastName, 'No lastname') AS LastName FROM dbo.Mechanics
COALESCE函数(多个参数)比ISNULL函数稍微慢一点(只有2个参数)