IF OBJECT_ID(N'dbo.设备管理_刀具寿命_明细_查询', N'P') IS NOT NULL
  DROP PROCEDURE dbo.设备管理_刀具寿命_明细_查询
GO

CREATE PROCEDURE dbo.设备管理_刀具寿命_明细_查询
  @设备编号 NVARCHAR(100) = N''
AS
BEGIN
  SET NOCOUNT ON

  SELECT
    LTRIM(RTRIM(所在工位号)) AS 设备编号,
    LTRIM(RTRIM(所在工位号)) AS 设备名称,
    ISNULL(名称, '') AS 刀具名称,
    ISNULL(刀具代码, '') AS 刀具代码,
    ISNULL(刀具组号, '') AS 刀具组号,
    ISNULL(规格, '') AS 规格,
    ISNULL(型号, '') AS 型号,
    CAST(ISNULL(刀具额定寿命, 0) AS DECIMAL(18, 2)) AS 额定寿命,
    CAST(ISNULL(已用寿命, 0) AS DECIMAL(18, 2)) AS 已用寿命,
    CAST(ISNULL(预警值1, 0) AS DECIMAL(18, 2)) AS 预警值1,
    CAST(ISNULL(刀具额定寿命, 0) - ISNULL(已用寿命, 0) AS DECIMAL(18, 2)) AS 剩余寿命,
    CASE
      WHEN ISNULL(刀具额定寿命, 0) > 0 AND ISNULL(已用寿命, 0) >= ISNULL(刀具额定寿命, 0) THEN N'报废'
      WHEN ISNULL(预警值1, 0) > 0 AND ISNULL(已用寿命, 0) >= ISNULL(预警值1, 0) THEN N'预警'
      ELSE N'正常'
    END AS 状态,
    所属工艺,
    采购日期,
    装刀到工位日期,
    操作时间
  FROM dbo.设备管理_刀具设备台账
  WHERE ISNULL(LTRIM(RTRIM(@设备编号)), '') = ''
     OR LTRIM(RTRIM(所在工位号)) = LTRIM(RTRIM(@设备编号))
  ORDER BY
    LTRIM(RTRIM(所在工位号)),
    CASE
      WHEN ISNULL(刀具额定寿命, 0) > 0 AND ISNULL(已用寿命, 0) >= ISNULL(刀具额定寿命, 0) THEN 3
      WHEN ISNULL(预警值1, 0) > 0 AND ISNULL(已用寿命, 0) >= ISNULL(预警值1, 0) THEN 2
      ELSE 1
    END DESC,
    ISNULL(名称, ''),
    ISNULL(刀具代码, '')
END
GO
