我在SQL Server 2012中使用SET和SELECT时遇到了一个问题。
使用以下SQL语句:
SELECT @CellNo= Complainants.CellNo FROM Complainants
INNER JOIN Complaints
ON Complainants.ComplainantID = Complaints.Complainant_ID
WHERE Complaints.ComplaintID = @ComplaintID
工作;但是当我使用以下语句时:
SET @CellNo= Complainants.CellNo from Complainants
INNER JOIN Complaints
ON Complainants.ComplainantID = Complaints.Complainant_ID
WHERE Complaints.ComplaintID = @ComplaintID
则不起作用;报告的错误是:
Error: Incorrect syntax near FROM
为什么我得到这个错误?
使用以下格式设置命令:
SET @CellNo= (Select Complainants.CellNo from Complainants
inner join Complaints
ON Complainants.ComplainantID = Complaints.Complainant_ID
Where Complaints.ComplaintID = @ComplaintID)
使用
SET @CellNo = (SELECT Complainants.CellNo
FROM Complainants INNER JOIN
Complaints ON Complainants.ComplainantID = Complaints.Complainant_ID
WHERE Complaints.ComplaintID = @ComplaintID)
这不是问题,这是它应该如何工作的。使用SET设置变量值,使用SELECT从表中选择数据。如果需要从列中读取数据,则必须使用SELECT。如建议的那样,使用set和subselect的组合可以工作,但会增加额外的代码。