我是sql的新手,我正在尝试连接两个表并合并值。 单独运行时,下面的Coalesce代码可以正常工作
Select @ContactName = COALESCE(@ContactName + ', ', '') + c.ContactName from contacts c inner join functions b on c.pid= b.pid
但是当我把整个代码组合起来时,它没有执行。有人可以建议如下。
select
a.*,
b.tfunction,
b.SSummary,
b.ContactType,
( Select @ContactName = COALESCE(@ContactName + ', ', '') + c.ContactName from contacts c inner join functions b on c.pid = b.pid),
( Select @Address = COALESCE(@Address + ', ', '') + c.Address from contacts c inner join functions b on c.pid = b.pid),
( Select @ContactPhone = COALESCE(@ContactPhone + ', ', '') + c.ContactPhone from contacts c inner join functions b on c.pid = b.pid),
( Select @ContactEmail = COALESCE(@ContactEmail + ', ', '') + c.ContactEmail from contacts c inner join functions b on c.pid = b.pid)
from contracts a
inner join functions b on a.pid = b.pid
错误详情
Msg 102, Level 15, State 1, Line 12
Incorrect syntax near '='.
Msg 102, Level 15, State 1, Line 13
Incorrect syntax near ','.
Msg 102, Level 15, State 1, Line 14
Incorrect syntax near ','.
Msg 102, Level 15, State 1, Line 15
Incorrect syntax near ')'.
ps: - 随意修改代码。
PS-我有所有4个属性的声明变量 - 堆栈溢出不允许我出于某种原因粘贴它们。
答案 0 :(得分:1)
这是您的查询:
select a.*, b.tfunction, b.SSummary, b.ContactType,
(Select @ContactName = COALESCE(@ContactName + ', ', '') + c.ContactName
from contacts c inner join
functions b
on c.pid = b.pid
),
(Select @Address = COALESCE(@Address + ', ', '') + c.Address
from contacts c inner join
functions b
on c.pid = b.pid
),
(Select @ContactPhone = COALESCE(@ContactPhone + ', ', '') + c.ContactPhone
from contacts c inner join
functions b
on c.pid = b.pid
),
( varchar(1000) Select @ContactEmail = COALESCE(@ContactEmail + ', ', '') + c.ContactEmail
from contacts c inner join
functions b
on c.pid = b.pid
)
from contracts a inner join
functions b
on a.pid = b.pid;
这有多个明显的语法错误:
varchar(1000)
只是挂在那里,好像你试图用C或其他东西进行演员。然后你有其他逻辑错误:
您似乎想要从联系人处获取事物列表。这在SQL Server中很痛苦,但这可能会让您走上正确的道路:
select a.*, b.tfunction, b.SSummary, b.ContactType,
stuff((select ', ', c.ContactName
from contacts c
where c.pid = b.pid
for xml path ('')
), 1, 2, '') as Contacts,
stuff((Select ', ' + c.Address
from contacts c
where c.pid = b.pid
for xml path ('')
), 1, 2, '') as Addresses,
. . .
from contracts a join
functions b
on a.pid = b.pid;
答案 1 :(得分:0)
问题可能在于您的INNER JOIN,FUNCTIONS中必须有一行才能看到任何结果。
如果您想要显示CONTACTS中的行,即使FUNCTIONS中的行不匹配,也要将INNER JOIN替换为LEFT JOIN。
Select
@ContactName = COALESCE(@ContactName + ', ', '') + c.ContactName
from contacts c
LEFT join functions b on c.pid= b.pid