我收到此错误(请参阅标题)。我该如何纠正这个:
SQL
use adventureworks
go
select si.CustomerID,
'myField' =
CASE
When (Select Top 1 FirstName,LastName From Person.Contact pc Where si.ContactID = pc.contactid ) is not null Then
Cast((Select Top 1 FirstName,LastName From Person.Contact pc Where si.ContactID = pc.contactid ) As varchar)
Else ''
END
from Sales.Individual si
where si.CustomerID=11000
答案 0 :(得分:1)
您正在尝试选择两个值并将它们视为一个表达式:
select top 1 FirstName, LastName ...
这可能应该改为这样:
select top 1 FirstName + ' ' + LastName ...
功能齐全的版本将是这样的:
select
si.CustomerID,
CASE
WHEN
(Select Top 1 FirstName + ' ' + LastName From Person.Contact pc Where si.ContactID = pc.contactid ) is not null
THEN
(Select Top 1 FirstName + ' ' + LastName From Person.Contact pc Where si.ContactID = pc.contactid )
Else ''
END [myField]
from
Sales.Individual si
where
si.CustomerID=11000
答案 1 :(得分:1)
修改查询
use adventureworks go
select si.CustomerID, 'myField' =
CASE When
(Select Top 1 FirstName From Person.Contact pc Where si.ContactID = pc.contactid ) is not null
Then
Cast((Select Top 1 FirstName
From Person.Contact pc Where si.ContactID = pc.contactid ) As varchar)
Else ''
END from Sales.Individual si where si.CustomerID=11000
错误是因为你选择了FirstName和LastName,所以要删除错误选择其中一个firstanme或lastname或两者合二为一个
例如
Select Top 1 FirstName+ ' ' + LastName as fullName
From Person.Contact pc Where si.ContactID = pc.
这将解决您的问题
答案 2 :(得分:1)
在查询中使用子查询时,SQL只能从一个记录返回一个字段。您可能想要连接这些字段,您可以这样做:
use adventureworks
go
select si.CustomerID,
'myField' =
CASE
When (Select Top 1 FirstName+ ' ' + LastName From Person.Contact pc Where si.ContactID = pc.contactid ) is not null Then
Cast((Select Top 1 FirstName+ ' ' + LastName From Person.Contact pc Where si.ContactID = pc.contactid ) As varchar)
Else ''
END
from Sales.Individual si
where si.CustomerID=11000
或者你可以在子查询中选择其中一个字段。