我想在我的proc中传递devicenumber作为参数,我必须从devicemaster表中按设备编号选择deviceid,从那个deviceid我必须从truck master中选择RegistrationNumber和currentlocation,从tripdetails选择distance,frocityid和tocity(表deviceid是常见的),但fromcityid和tocityid有一个cityname,它出现在regionmaster表中
因此,通过传递DeviceNUmber作为参数,我想要一个具有RegisterNumber,currentlocation,distance,fromcityname和tocityname列的结果集。
我收到此错误:
Msg 209,Level 16,State 1,Procedure PROC_GMAPSDATA,Line 24 不明确的列名'DEVICEID'。
程序如何:
ALTER PROCEDURE [dbo].[PROC_GMAPSDATA]
(
@DEVICENUMBER varchar(50)
)
AS
BEGIN
DECLARE @DEVICEID INT
SET @DEVICEID=(SELECT DEVICEID FROM DEVICEMASTER WHERE DEVICENO= @DEVICENUMBER)
SELECT TM.REGISTRATIONNUMBER ,
TM.CURRENTLOCATION,
TM.CURRENTLATLNG,
RM.CityName AS FromCity,
RM1.CityName AS ToCity,
TD.DISTANCE
FROM TRUCKMASTER TM
JOIN TRIPDETAIL TD ON TM.DEVICEID=TD.DEVICEID
JOIN REGIONMASTER RM ON RM.REGIONID =TD.FROMCTYID
JOIN REGIONMASTER RM1 ON RM1.REGIONID=TD.TOCTYID
WHERE DEVICEID IN (SELECT DEVICEID FROM DEVICEMASTER WHERE DEVICENO= @DEVICENUMBER)
END
GO
答案 0 :(得分:2)
我希望您的错误消息来自WHERE DEVICEID IN ...
,其中您没有该列的别名。查询并不知道您的意思是TM.DEVICEID
还是TD.DEVICEID
,所以如果您将最后一行更改为下面的一行,则应该没问题:
WHERE TM.DEVICEID IN (SELECT DEVICEID FROM DEVICEMASTER WHERE DEVICENO = @DEVICENUMBER)
答案 1 :(得分:1)
我已将您的查询格式化如下。别名包含在Where
条款中。始终确保使用您在查询中定义的变量
ALTER PROCEDURE [dbo].[PROC_GMAPSDATA]
(
@DEVICENUMBER varchar(50)
)
AS
BEGIN
SET NOCOUNT ON;
DECLARE @DEVICEID INT
SET @DEVICEID=(SELECT DEVICEID FROM DEVICEMASTER WHERE DEVICENO= @DEVICENUMBER)
SELECT TM.REGISTRATIONNUMBER ,
TM.CURRENTLOCATION,
TM.CURRENTLATLNG,
RM.CityName AS FromCity,
RM1.CityName AS ToCity,
TD.DISTANCE
FROM TRUCKMASTER TM
INNER JOIN TRIPDETAIL TD
ON TM.DEVICEID = TD.DEVICEID
INNER JOIN REGIONMASTER RM
ON RM.REGIONID = TD.FROMCTYID
INNER JOIN REGIONMASTER RM1
ON RM1.REGIONID = TD.TOCTYID
WHERE TM.DEVICEID = @DEVICEID;
SET NOCOUNT OFF;
END