坚持'必须声明标量变量'

时间:2017-08-03 04:33:41

标签: sql sql-server tsql

我已在我的查询中声明参数,但是当我执行它时,出现错误

  

必须声明标量变量

我该怎么办?

 USE IMS_LOCATION

 SELECT TOP(100000)
     COALESCE(a.LOT_ID, b.LOT_ID, c.LOT_ID, d.LOT_ID) AS LotId, 
     COALESCE(a.CheckIn, b.CheckIn, c.CheckIn, d.CheckIn) AS CheckIn,
     COALESCE(a.CheckOut, b.CheckOut, c.CheckOut, d.CheckOut) AS CheckOut,
     COALESCE(a.StatusDesc, b.StatusDesc, c.StatusDesc, d.StatusDesc) AS 
 StatusDesc
 FROM
     LOT_LOC_BOND a
 LEFT JOIN 
     LOT_LOC_IEBT b ON a.LOT_ID = b.LOT_ID AND a.LOT_ID = @lotId,
     LOT_LOC_MBT c 
 LEFT JOIN 
     LOT_LOC_SEAL d ON c.LOT_ID = d.LOT_ID 

1 个答案:

答案 0 :(得分:0)

我上面的评论表明您的问题有以下解决方案。

CREATE FUNCTION getLotInfo(@suppliedLotId INTEGER)
RETURNS TABLE 
AS
RETURN
( 
    SELECT 
        combinedLotId, 
        combinedCheckIn, 
        combinedCheckOut, 
        combinedStatusDesc, 
        originTable 
    FROM (
        SELECT 
            LOT_ID AS combinedLotId, 
            CheckIn AS combinedCheckIn, 
            CheckOut AS combinedCheckOut, 
            StatusDesc AS combinedStatusDesc, 
            'LOT_LOC_BOND' AS originTable
        FROM LOT_LOC_BOND 
        UNION SELECT 
            LOT_ID, CheckIn, CheckOut, StatusDesc, 'LOT_LOC_IEBT'
        FROM LOT_LOC_IEBT 
        UNION SELECT 
            LOT_ID, CheckIn, CheckOut, StatusDesc, 'LOT_LOC_MBT'
        FROM LOT_LOC_MBT 
        UNION SELECT 
            LOT_ID, CheckIn, CheckOut, StatusDesc, 'LOT_LOC_SEAL'
        FROM LOT_LOC_SEAL 
    ) AS results
    WHERE combinedLotId = @suppliedLotId
);

该功能可能无法完美满足您的需求,但它可以给您一个想法。