USE [master]
GO
/****** Object:  Database [YL_MESDB]    Script Date: 2026/5/18 8:58:57 ******/
CREATE DATABASE [YL_MESDB]
 CONTAINMENT = NONE
 ON  PRIMARY 
( NAME = N'YL_MESDB', FILENAME = N'D:\sqlData\YL_MESDB.mdf' , SIZE = 7044480KB , MAXSIZE = UNLIMITED, FILEGROWTH = 65536KB )
 LOG ON 
( NAME = N'YL_MESDB_log', FILENAME = N'D:\sqlDataLog\YL_MESDB_log.ldf' , SIZE = 269688832KB , MAXSIZE = 2048GB , FILEGROWTH = 65536KB )
 WITH CATALOG_COLLATION = DATABASE_DEFAULT
GO
ALTER DATABASE [YL_MESDB] SET COMPATIBILITY_LEVEL = 150
GO
IF (1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled'))
begin
EXEC [YL_MESDB].[dbo].[sp_fulltext_database] @action = 'enable'
end
GO
ALTER DATABASE [YL_MESDB] SET ANSI_NULL_DEFAULT OFF 
GO
ALTER DATABASE [YL_MESDB] SET ANSI_NULLS OFF 
GO
ALTER DATABASE [YL_MESDB] SET ANSI_PADDING OFF 
GO
ALTER DATABASE [YL_MESDB] SET ANSI_WARNINGS OFF 
GO
ALTER DATABASE [YL_MESDB] SET ARITHABORT OFF 
GO
ALTER DATABASE [YL_MESDB] SET AUTO_CLOSE OFF 
GO
ALTER DATABASE [YL_MESDB] SET AUTO_SHRINK OFF 
GO
ALTER DATABASE [YL_MESDB] SET AUTO_UPDATE_STATISTICS ON 
GO
ALTER DATABASE [YL_MESDB] SET CURSOR_CLOSE_ON_COMMIT OFF 
GO
ALTER DATABASE [YL_MESDB] SET CURSOR_DEFAULT  GLOBAL 
GO
ALTER DATABASE [YL_MESDB] SET CONCAT_NULL_YIELDS_NULL OFF 
GO
ALTER DATABASE [YL_MESDB] SET NUMERIC_ROUNDABORT OFF 
GO
ALTER DATABASE [YL_MESDB] SET QUOTED_IDENTIFIER OFF 
GO
ALTER DATABASE [YL_MESDB] SET RECURSIVE_TRIGGERS OFF 
GO
ALTER DATABASE [YL_MESDB] SET  DISABLE_BROKER 
GO
ALTER DATABASE [YL_MESDB] SET AUTO_UPDATE_STATISTICS_ASYNC OFF 
GO
ALTER DATABASE [YL_MESDB] SET DATE_CORRELATION_OPTIMIZATION OFF 
GO
ALTER DATABASE [YL_MESDB] SET TRUSTWORTHY OFF 
GO
ALTER DATABASE [YL_MESDB] SET ALLOW_SNAPSHOT_ISOLATION OFF 
GO
ALTER DATABASE [YL_MESDB] SET PARAMETERIZATION SIMPLE 
GO
ALTER DATABASE [YL_MESDB] SET READ_COMMITTED_SNAPSHOT OFF 
GO
ALTER DATABASE [YL_MESDB] SET HONOR_BROKER_PRIORITY OFF 
GO
ALTER DATABASE [YL_MESDB] SET RECOVERY FULL 
GO
ALTER DATABASE [YL_MESDB] SET  MULTI_USER 
GO
ALTER DATABASE [YL_MESDB] SET PAGE_VERIFY CHECKSUM  
GO
ALTER DATABASE [YL_MESDB] SET DB_CHAINING OFF 
GO
ALTER DATABASE [YL_MESDB] SET FILESTREAM( NON_TRANSACTED_ACCESS = OFF ) 
GO
ALTER DATABASE [YL_MESDB] SET TARGET_RECOVERY_TIME = 60 SECONDS 
GO
ALTER DATABASE [YL_MESDB] SET DELAYED_DURABILITY = DISABLED 
GO
ALTER DATABASE [YL_MESDB] SET ACCELERATED_DATABASE_RECOVERY = OFF  
GO
EXEC sys.sp_db_vardecimal_storage_format N'YL_MESDB', N'ON'
GO
ALTER DATABASE [YL_MESDB] SET QUERY_STORE = OFF
GO
USE [YL_MESDB]
GO
/****** Object:  UserDefinedFunction [dbo].[计算班次重叠秒数]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[计算班次重叠秒数] 
(
    @开始时间 datetime,
    @结束时间 datetime,
    @班次开始 time,
    @班次结束 time
)
RETURNS int
AS
BEGIN
    DECLARE @重叠秒数 int = 0
    
    -- 如果输入时间为NULL，返回0
    IF @开始时间 IS NULL OR @结束时间 IS NULL OR @班次开始 IS NULL OR @班次结束 IS NULL
        RETURN 0
    
    -- 确保结束时间大于开始时间
    IF @结束时间 <= @开始时间
        RETURN 0
    
    -- 将班次时间转换为具体的日期时间
    DECLARE @当前日期 date = CAST(@开始时间 AS date)
    DECLARE @结束日期 date = CAST(@结束时间 AS date)
    DECLARE @天数差 int = DATEDIFF(DAY, @当前日期, @结束日期)
    
    -- 如果天数差大于3，可能有问题，限制计算范围
    IF @天数差 > 3
        SET @天数差 = 3
    
    DECLARE @循环次数 int = @天数差 + 1  -- 包括开始当天
    
    -- 循环处理每一天
    WHILE @循环次数 > 0
    BEGIN
        -- 计算当天的班次开始和结束时间
        DECLARE @当天班次开始 datetime = CAST(@当前日期 AS datetime) + CAST(@班次开始 AS datetime)
        DECLARE @当天班次结束 datetime = CAST(@当前日期 AS datetime) + CAST(@班次结束 AS datetime)
        
        -- 处理跨天的班次（如晚班16:30-00:30）
        IF @班次结束 < @班次开始
        BEGIN
            SET @当天班次结束 = DATEADD(DAY, 1, @当天班次结束)
        END
        
        -- 计算重叠时间
        DECLARE @实际开始 datetime = 
            CASE 
                WHEN @开始时间 > @当天班次开始 THEN @开始时间 
                ELSE @当天班次开始 
            END
        
        DECLARE @实际结束 datetime = 
            CASE 
                WHEN @结束时间 < @当天班次结束 THEN @结束时间 
                ELSE @当天班次结束 
            END
        
        -- 计算重叠秒数（只计算正数部分）
        IF @实际开始 < @实际结束
        BEGIN
            SET @重叠秒数 = @重叠秒数 + DATEDIFF(SECOND, @实际开始, @实际结束)
        END
        
        -- 处理下一天
        SET @当前日期 = DATEADD(DAY, 1, @当前日期)
        SET @循环次数 = @循环次数 - 1
    END
    
    -- 如果为负数则返回0
    IF @重叠秒数 < 0 SET @重叠秒数 = 0
    
    RETURN @重叠秒数
END
GO
/****** Object:  Table [dbo].[MES_资源主数据]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[MES_资源主数据](
	[VisCode] [nvarchar](50) NOT NULL,
	[Name] [nvarchar](200) NULL,
	[ForeignName] [nvarchar](200) NOT NULL,
	[Type] [nvarchar](50) NOT NULL,
	[ResourceGroup] [int] NOT NULL,
	[UnitOfMeasure] [nvarchar](100) NOT NULL,
	[IssueMethod] [nvarchar](50) NOT NULL,
	[Active] [nvarchar](50) NOT NULL,
	[Remarks] [text] NULL,
	[Allocation] [nvarchar](50) NOT NULL,
	[SyncTime] [datetime] NULL,
 CONSTRAINT [PK__ORSC__00DF9DD5FB0E8B55] PRIMARY KEY CLUSTERED 
(
	[VisCode] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object:  View [dbo].[View_基础数据_工位]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE VIEW [dbo].[View_基础数据_工位]
AS
SELECT   VisCode, Name, SyncTime
FROM      dbo.MES_资源主数据
WHERE   (Type = 'rtMachine') AND (Active = 'tYES') AND (IssueMethod = 'rimManual') OR
                (Name = '外协')
GO
/****** Object:  Table [dbo].[生产管理_工时校验_校验工时表]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[生产管理_工时校验_校验工时表](
	[AID] [int] IDENTITY(1,1) NOT NULL,
	[操作类别编号] [int] NULL,
	[操作类别] [nvarchar](50) NULL,
	[阶段标识] [int] NULL,
	[工序名称] [nvarchar](50) NULL,
	[工位编号] [nvarchar](50) NULL,
	[工位名称] [nvarchar](50) NULL,
	[操作人] [nvarchar](50) NULL,
	[合同号] [nvarchar](50) NULL,
	[订单编号] [nvarchar](50) NULL,
	[物料编号] [nvarchar](50) NULL,
	[物料描述] [nvarchar](50) NULL,
	[操作数值] [int] NULL,
	[操作内容] [nvarchar](500) NULL,
	[操作描述] [nvarchar](2000) NULL,
	[TaskAID] [bigint] NULL,
	[开始时间] [datetime] NULL,
	[结束时间] [datetime] NULL,
	[工时] [int] NULL,
	[报工日期] [date] NULL,
	[已报工] [int] NULL,
	[不装配] [nvarchar](50) NULL,
	[最后编辑人] [nvarchar](50) NULL,
	[最后编辑时间] [datetime] NULL,
	[报工记录id] [int] NULL,
	[计算详情] [nvarchar](max) NULL,
	[上传工时] [decimal](18, 2) NULL,
	[工时类型] [nvarchar](20) NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object:  Table [dbo].[物料基础数据_零件图纸]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[物料基础数据_零件图纸](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[num] [nvarchar](100) NOT NULL,
	[uid] [nvarchar](100) NULL,
	[name] [nvarchar](100) NULL,
	[suffix] [nvarchar](50) NULL,
	[是否启用] [int] NULL,
	[worker] [nvarchar](100) NULL,
	[uploadTime] [nvarchar](100) NULL,
 CONSTRAINT [PK_物料基础数据_零件图纸] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[MES_接口_生产计划]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[MES_接口_生产计划](
	[AID] [int] IDENTITY(1,1) NOT NULL,
	[订单编号] [int] NOT NULL,
	[合同号] [nvarchar](50) NULL,
	[订单类型] [nvarchar](50) NULL,
	[订单状态] [nvarchar](50) NULL,
	[物料编号] [nvarchar](500) NULL,
	[物料描述] [nvarchar](500) NULL,
	[计划数量] [decimal](16, 2) NULL,
	[计量单位] [nvarchar](50) NULL,
	[下达日期] [datetime] NULL,
	[计划开始] [datetime] NULL,
	[计划完成] [datetime] NULL,
	[项目代码] [nvarchar](50) NULL,
	[备注] [nvarchar](500) NULL,
	[重量] [decimal](19, 6) NULL,
	[占用情况] [nvarchar](50) NULL,
	[加急状态] [int] NULL,
	[排产状态] [int] NULL,
	[排产时间] [datetime] NULL,
	[同步时间] [datetime] NULL,
	[任务状态] [int] NULL,
	[标准工艺] [int] NULL,
	[生产工艺] [int] NULL,
	[齐套] [float] NULL,
	[自制件属性] [nvarchar](50) NULL,
	[周转单打印次数] [int] NULL,
	[单据状态] [nvarchar](50) NULL,
	[预计齐套时间] [datetime] NULL,
	[发料状态] [nvarchar](50) NULL,
	[拣配状态] [nvarchar](50) NULL,
	[计划号] [nvarchar](50) NULL,
	[加急数量] [decimal](19, 6) NULL,
	[发货状态] [nvarchar](50) NULL,
	[要求发货日期] [datetime] NULL,
	[加急总数] [decimal](19, 6) NULL,
	[入库数量] [decimal](19, 6) NULL,
	[确认状态] [nvarchar](50) NULL,
 CONSTRAINT [PK_MES_接口_生产计划] PRIMARY KEY CLUSTERED 
(
	[订单编号] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[MES_接口_生产计划_生产任务]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[MES_接口_生产计划_生产任务](
	[AID] [bigint] IDENTITY(1,1) NOT NULL,
	[订单编号] [int] NOT NULL,
	[订单行号] [int] NOT NULL,
	[订单拆分内码] [int] NOT NULL,
	[任务概述] [nvarchar](500) NULL,
	[物料编码] [nvarchar](500) NULL,
	[物料名称] [nvarchar](500) NULL,
	[基本数量] [decimal](19, 6) NULL,
	[计划数量] [decimal](19, 6) NULL,
	[已发货数量] [decimal](19, 6) NULL,
	[订单发货类型] [nvarchar](50) NULL,
	[仓库代码] [nvarchar](50) NULL,
	[可视订单] [int] NULL,
	[物料类型] [nvarchar](50) NULL,
	[阶段标识] [int] NULL,
	[工序名称] [nvarchar](50) NULL,
	[顺序编号] [int] NULL,
	[性质] [nvarchar](50) NULL,
	[总工时] [decimal](16, 2) NULL,
	[行文本备注] [nvarchar](500) NULL,
	[不装配] [nvarchar](50) NULL,
	[指派对象编号] [nvarchar](50) NULL,
	[指派对象] [nvarchar](50) NULL,
	[指派数量] [decimal](16, 2) NULL,
	[计划开始时间] [datetime] NULL,
	[计划完成时间] [datetime] NULL,
	[最晚开始时间] [datetime] NULL,
	[派工状态] [int] NULL,
	[派工时间] [datetime] NULL,
	[派工操作人] [nvarchar](50) NULL,
	[任务状态] [int] NULL,
	[开工时间] [datetime] NULL,
	[完工时间] [datetime] NULL,
	[修改时间] [datetime] NULL,
	[外协通知] [int] NULL,
	[优先级] [nvarchar](50) NULL,
	[未完成说明] [nvarchar](500) NULL,
	[派工特殊说明] [nvarchar](500) NULL,
	[最后编辑人] [nvarchar](50) NULL,
	[最后编辑时间] [datetime] NULL,
	[完成数量] [int] NULL,
	[合格数量] [int] NULL,
	[不合格数量] [int] NULL,
	[让步放行数量] [int] NULL,
	[报废数量] [int] NULL,
	[可执行] [int] NULL,
	[收料] [int] NULL,
	[收料数量] [int] NULL,
	[开工] [int] NULL,
	[首检] [int] NULL,
	[巡检] [int] NULL,
	[进度] [decimal](16, 2) NULL,
	[序检] [int] NULL,
	[测试] [int] NULL,
	[入库] [int] NULL,
	[加工状态] [int] NULL,
	[操作时间] [datetime] NULL,
	[排产状态] [int] NULL,
	[二次派工] [nvarchar](500) NULL,
	[外协打印次数] [int] NULL,
	[外协备注] [nvarchar](500) NULL,
	[单重] [nvarchar](50) NULL,
	[外协分组] [nvarchar](50) NULL,
	[打印数量] [nvarchar](50) NULL,
	[本次检数] [nvarchar](50) NULL,
 CONSTRAINT [PK_MES_接口_生产计划_生产任务] PRIMARY KEY CLUSTERED 
(
	[AID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY],
 CONSTRAINT [UK_订单唯一组合] UNIQUE NONCLUSTERED 
(
	[订单编号] ASC,
	[订单行号] ASC,
	[订单拆分内码] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  View [dbo].[View_生产订单_MES]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE VIEW [dbo].[View_生产订单_MES]
AS
SELECT    a.订单编号, a.合同号, b.订单拆分内码, a.订单类型, a.订单状态, a.物料编号, a.物料描述, b.计划数量 AS 工序计划数量, a.计量单位, a.下达日期, a.计划开始, a.计划完成, a.项目代码, a.备注, 
               a.重量, a.占用情况, a.加急状态, a.同步时间, b.订单行号, b.物料编码, b.物料名称, b.基本数量, b.计划数量, b.已发货数量, b.订单发货类型, b.仓库代码, b.可视订单, b.物料类型, b.阶段标识, 
               b.工序名称, b.顺序编号, b.性质, b.总工时, b.行文本备注, b.不装配, b.指派对象, b.指派数量, b.计划开始时间, b.计划完成时间, b.最晚开始时间, b.派工状态, b.派工时间, b.任务状态, 
               b.修改时间, b.外协通知, b.优先级, b.未完成说明, b.派工特殊说明, b.最后编辑人, b.最后编辑时间, b.可执行, b.收料, b.收料数量, b.开工, b.首检, b.巡检, b.完成数量, b.进度, b.序检, b.测试, 
               b.入库, b.AID AS TaskAID, b.加工状态, b.操作时间, b.开工时间, b.完工时间, b.合格数量, b.不合格数量, b.让步放行数量, b.报废数量, a.计划数量 AS 计划数量订单, b.排产状态, 
               a.自制件属性, b.二次派工, a.周转单打印次数, b.外协打印次数, b.单重, b.外协备注, a.齐套, a.单据状态, a.生产工艺, a.标准工艺, a.任务状态 AS Expr1, b.指派对象编号, 
               dbo.MES_资源主数据.VisCode, a.发料状态, a.拣配状态, a.计划号, b.外协分组, a.加急数量, a.发货状态, a.要求发货日期, a.加急总数, b.打印数量, a.入库数量, 
               dbo.物料基础数据_零件图纸.worker, b.本次检数
FROM       dbo.MES_接口_生产计划_生产任务 AS b LEFT OUTER JOIN
               dbo.物料基础数据_零件图纸 ON b.物料编码 = dbo.物料基础数据_零件图纸.num LEFT OUTER JOIN
               dbo.MES_资源主数据 ON b.指派对象 = dbo.MES_资源主数据.Name RIGHT OUTER JOIN
               dbo.MES_接口_生产计划 AS a ON b.订单编号 = a.订单编号
WHERE    (b.物料类型 = 'pit_Resource') AND (a.单据状态 IS NULL)
GO
/****** Object:  Table [dbo].[工位人员绑定表]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[工位人员绑定表](
	[绑定编号] [int] IDENTITY(1,1) NOT NULL,
	[工位号] [nvarchar](50) NOT NULL,
	[人员编号] [int] NOT NULL,
	[绑定时间] [datetime] NULL,
	[绑定人] [nvarchar](50) NULL,
	[绑定状态] [int] NULL,
PRIMARY KEY CLUSTERED 
(
	[绑定编号] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[登录基础数据_人员信息]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[登录基础数据_人员信息](
	[Personnel_Number] [int] IDENTITY(1,1) NOT NULL,
	[account] [nvarchar](50) NOT NULL,
	[password] [nvarchar](50) NULL,
	[Personnel_Name] [nvarchar](50) NOT NULL,
	[Departments_ID] [int] NULL,
	[Quit] [int] NULL,
	[OrgUnit] [int] NULL,
	[Cost_Center] [nvarchar](50) NULL,
	[Business_Area] [nvarchar](50) NULL,
	[PSG] [nvarchar](50) NULL,
	[Job_Title] [nvarchar](50) NULL,
	[Payroll_Area] [nvarchar](50) NULL,
	[Chinese_Name] [nvarchar](50) NULL,
 CONSTRAINT [人事档案管理_人员名单] PRIMARY KEY CLUSTERED 
(
	[Personnel_Number] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY],
 CONSTRAINT [account 唯一键] UNIQUE NONCLUSTERED 
(
	[account] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY],
 CONSTRAINT [IX_SCHAEFFLER_Personnel] UNIQUE NONCLUSTERED 
(
	[Personnel_Number] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  View [dbo].[View_工位人员绑定数]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE VIEW [dbo].[View_工位人员绑定数]
AS
SELECT DISTINCT a.人员编号, ISNULL(c.Personnel_Name, '未知') AS 人员姓名,
                   (SELECT    COUNT(DISTINCT b2.Name) AS Expr1
                   FROM       dbo.工位人员绑定表 AS a2 LEFT OUTER JOIN
                                  dbo.MES_资源主数据 AS b2 ON a2.工位号 = b2.VisCode
                   WHERE    (a2.人员编号 = a.人员编号) AND (a2.绑定状态 = 1) AND (b2.Name IS NOT NULL)) AS 绑定设备数
FROM       dbo.工位人员绑定表 AS a LEFT OUTER JOIN
               dbo.MES_资源主数据 AS b ON a.工位号 = b.VisCode LEFT OUTER JOIN
               dbo.登录基础数据_人员信息 AS c ON a.人员编号 = c.Personnel_Number
WHERE    (a.绑定状态 = 1) AND (b.Name IS NOT NULL)
GO
/****** Object:  Table [dbo].[YL_加工中心_操作记录表]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[YL_加工中心_操作记录表](
	[AID] [int] IDENTITY(1,1) NOT NULL,
	[操作类别编号] [int] NULL,
	[操作类别] [nvarchar](50) NULL,
	[阶段标识] [int] NULL,
	[工序名称] [nvarchar](50) NULL,
	[工位编号] [nvarchar](50) NULL,
	[工位名称] [nvarchar](50) NULL,
	[操作人] [nvarchar](50) NULL,
	[合同号] [nvarchar](50) NULL,
	[订单编号] [nvarchar](50) NULL,
	[物料编号] [nvarchar](50) NULL,
	[物料描述] [nvarchar](50) NULL,
	[操作数值] [int] NULL,
	[操作内容] [nvarchar](500) NULL,
	[操作描述] [nvarchar](2000) NULL,
	[TaskAID] [bigint] NULL,
	[开始时间] [datetime] NULL,
	[结束时间] [datetime] NULL,
	[工时] [int] NULL,
	[报工日期] [date] NULL,
	[已报工] [int] NULL,
	[不装配] [nvarchar](50) NULL,
	[最后编辑人] [nvarchar](50) NULL,
	[最后编辑时间] [datetime] NULL,
	[关联开始记录ID] [int] NULL,
	[关联暂停记录ID] [int] NULL,
	[关联操作类型] [nvarchar](50) NULL,
	[暂停时间] [datetime] NULL,
	[暂停时长] [int] NULL,
	[暂停总时长] [int] NULL,
	[总时长] [int] NULL,
	[实际工时] [int] NULL,
	[备注] [nvarchar](500) NULL,
	[工序说明] [nvarchar](500) NULL,
	[异常说明] [nvarchar](500) NULL,
	[是否更新] [int] NULL,
	[班次标准工时] [int] NOT NULL,
	[班次] [nvarchar](50) NULL
) ON [PRIMARY]
GO
/****** Object:  View [dbo].[View_生产工时视图]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/* 按开始时间降序排序*/
CREATE VIEW [dbo].[View_生产工时视图]
AS
SELECT  TOP (100) PERCENT ISNULL(c.AID, o.AID) AS AID, ISNULL(c.操作类别编号, o.操作类别编号) AS 操作类别编号, ISNULL(c.操作类别, o.操作类别) 
               AS 操作类别, ISNULL(c.阶段标识, o.阶段标识) AS 阶段标识, ISNULL(c.工序名称, o.工序名称) AS 工序名称, ISNULL(c.工位编号, o.工位编号) 
               AS 工位编号, ISNULL(c.工位名称, o.工位名称) AS 工位名称, ISNULL(c.操作人, o.操作人) AS 操作人, ISNULL(c.合同号, o.合同号) AS 合同号, 
               ISNULL(c.订单编号, o.订单编号) AS 订单号, ISNULL(c.物料编号, o.物料编号) AS 产品编码, ISNULL(c.物料描述, o.物料描述) AS 产品名称, 
               ISNULL(c.操作数值, o.操作数值) AS 操作数值, ISNULL(c.操作内容, o.操作内容) AS 操作内容, ISNULL(c.操作描述, o.操作描述) AS 操作描述, 
               ISNULL(c.TaskAID, o.TaskAID) AS TaskAID, ISNULL(c.开始时间, o.开始时间) AS 开始时间, ISNULL(c.结束时间, o.结束时间) AS 结束时间, ISNULL(c.工时, 
               o.实际工时) AS 加工工时, ISNULL(o.总时长, 0) AS 总时长, ISNULL(c.报工日期, o.报工日期) AS 报工日期, ISNULL(c.已报工, o.已报工) AS 已报工, 
               ISNULL(c.不装配, o.不装配) AS 不装配, CASE WHEN c.AID IS NOT NULL THEN 1 ELSE 0 END AS 已校验, ISNULL(c.最后编辑人, o.最后编辑人) 
               AS 最后编辑人, ISNULL(c.最后编辑时间, o.最后编辑时间) AS 最后编辑时间, m.订单行号, m.顺序编号, m.VisCode, c.AID AS Expr1, m.计划数量, 
               m.完成数量, m.自制件属性, s.合同号 AS 订单合同号, s.入库数量, s.计划数量 AS Expr2, s.单据状态, s.确认状态, 
               ISNULL(dbo.View_工位人员绑定数.绑定设备数, 0) AS 绑定设备数, o.工序说明, o.异常说明, o.工位名称 AS Expr3, o.班次标准工时,
                   (SELECT  ISNULL(MIN(班次标准工时), 0) AS Expr1
                   FROM     dbo.YL_加工中心_操作记录表 AS b
                   WHERE   (操作人 = ISNULL(c.操作人, o.操作人)) AND (操作类别 = '报工') AND (CONVERT(DATE, 开始时间) = CONVERT(DATE, ISNULL(c.开始时间, 
                                  o.开始时间)))) AS 当日班次最小标准工时, o.班次
FROM     dbo.YL_加工中心_操作记录表 AS o LEFT OUTER JOIN
               dbo.View_工位人员绑定数 ON o.操作人 = dbo.View_工位人员绑定数.人员姓名 LEFT OUTER JOIN
               dbo.生产管理_工时校验_校验工时表 AS c ON o.AID = c.报工记录id LEFT OUTER JOIN
               dbo.View_生产订单_MES AS m ON ISNULL(c.TaskAID, o.TaskAID) = m.TaskAID LEFT OUTER JOIN
               dbo.MES_接口_生产计划 AS s ON ISNULL(c.订单编号, o.订单编号) = s.订单编号
WHERE   (o.工位名称 <> '外协') AND (o.操作类别 <> '报工' OR
               ISNULL(c.结束时间, o.结束时间) IS NOT NULL) AND (c.AID IS NOT NULL OR
               o.操作类别 <> '收料') AND (c.AID IS NOT NULL OR
               o.操作内容 NOT IN ('开始加工', '辅助开始') OR
               o.结束时间 IS NOT NULL OR
               NOT EXISTS
                   (SELECT  1 AS Expr1
                   FROM     dbo.YL_加工中心_操作记录表 AS t2
                   WHERE   (操作内容 IN ('报工', '辅助结束')) AND (TaskAID = o.TaskAID) AND (开始时间 = o.开始时间))) AND (o.操作内容 NOT IN ('辅助结束') OR
               NOT EXISTS
                   (SELECT  1 AS Expr1
                   FROM     dbo.YL_加工中心_操作记录表 AS p
                   WHERE   (操作内容 = '辅助结束') AND (TaskAID = o.TaskAID) AND (结束时间 IS NULL))) AND (o.操作内容 NOT IN ('开始加工', '辅助开始') OR
               NOT EXISTS
                   (SELECT  1 AS Expr1
                   FROM     dbo.YL_加工中心_操作记录表 AS p
                   WHERE   (操作内容 = '暂停') AND (TaskAID = o.TaskAID) AND (结束时间 = o.开始时间) AND (操作人 = o.操作人))) AND (o.操作数值 IS NOT NULL OR
               o.操作内容 IN ('开始加工', '辅助开始') AND o.结束时间 IS NULL OR
               o.操作描述 <> '')
GO
/****** Object:  View [dbo].[View_图纸视图]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE VIEW [dbo].[View_图纸视图]
AS
SELECT  t1.id, t1.num, t1.uid, t1.name, t1.suffix, t1.是否启用, t1.worker, t1.uploadTime, t2.物料名称 AS 物料描述, t2.U_BuyToPrint
FROM     dbo.物料基础数据_零件图纸 AS t1 LEFT OUTER JOIN
               SAP.SBO_YL.dbo.UBT_OITM AS t2 ON t1.num = t2.物料编码
GO
/****** Object:  Table [dbo].[YL_质量检验_质检记录]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[YL_质量检验_质检记录](
	[QT_AID] [bigint] IDENTITY(1,1) NOT NULL,
	[TaskAID] [bigint] NULL,
	[检测类型编号] [int] NULL,
	[质检类型] [nvarchar](50) NULL,
	[零件编码] [nvarchar](200) NULL,
	[零件名称] [nvarchar](200) NULL,
	[内部合同号] [nvarchar](100) NULL,
	[计划号] [int] NULL,
	[工序名称] [nvarchar](100) NULL,
	[计划生产数] [int] NULL,
	[检验数量] [decimal](18, 4) NULL,
	[合格数] [decimal](18, 4) NULL,
	[不合格数] [decimal](18, 4) NULL,
	[检测人] [nvarchar](50) NULL,
	[检测时间] [datetime] NULL,
	[检测说明] [nvarchar](2000) NULL,
	[行号] [int] NULL,
	[订单类型] [nvarchar](50) NULL,
	[到货数] [decimal](18, 4) NULL,
	[转至] [int] NOT NULL,
	[完成] [int] NOT NULL,
	[放行数量] [int] NOT NULL,
 CONSTRAINT [PK_YL_质量检验_质检记录] PRIMARY KEY CLUSTERED 
(
	[QT_AID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  View [dbo].[View_质量检验_质检记录_外协收检]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE VIEW [dbo].[View_质量检验_质检记录_外协收检]
AS
SELECT   dbo.YL_质量检验_质检记录.QT_AID AS Expr1, dbo.YL_质量检验_质检记录.TaskAID AS Expr2, 
                dbo.YL_质量检验_质检记录.检测类型编号 AS Expr3, dbo.YL_质量检验_质检记录.质检类型 AS Expr4, 
                dbo.YL_质量检验_质检记录.零件编码 AS Expr5, dbo.YL_质量检验_质检记录.零件名称 AS Expr6, 
                dbo.YL_质量检验_质检记录.内部合同号 AS Expr7, dbo.YL_质量检验_质检记录.计划号 AS Expr8, 
                dbo.YL_质量检验_质检记录.工序名称 AS Expr9, dbo.YL_质量检验_质检记录.计划生产数 AS Expr10, 
                dbo.YL_质量检验_质检记录.检验数量 AS Expr11, dbo.YL_质量检验_质检记录.合格数 AS Expr12, 
                dbo.YL_质量检验_质检记录.不合格数 AS Expr13, dbo.YL_质量检验_质检记录.检测人 AS Expr14, 
                dbo.YL_质量检验_质检记录.检测时间 AS Expr15, dbo.YL_质量检验_质检记录.检测说明 AS Expr16, 
                dbo.YL_质量检验_质检记录.行号 AS Expr17, dbo.YL_质量检验_质检记录.订单类型 AS Expr18, 
                dbo.YL_质量检验_质检记录.QT_AID, dbo.YL_质量检验_质检记录.TaskAID, dbo.YL_质量检验_质检记录.检测类型编号, 
                dbo.YL_质量检验_质检记录.质检类型, dbo.YL_质量检验_质检记录.零件编码, dbo.YL_质量检验_质检记录.零件名称, 
                dbo.YL_质量检验_质检记录.内部合同号, dbo.YL_质量检验_质检记录.计划号, dbo.YL_质量检验_质检记录.工序名称, 
                dbo.YL_质量检验_质检记录.计划生产数, dbo.YL_质量检验_质检记录.检验数量, dbo.YL_质量检验_质检记录.合格数, 
                dbo.YL_质量检验_质检记录.不合格数, dbo.YL_质量检验_质检记录.检测人, dbo.YL_质量检验_质检记录.检测时间, 
                dbo.YL_质量检验_质检记录.检测说明, dbo.YL_质量检验_质检记录.行号, dbo.YL_质量检验_质检记录.订单类型, 
                dbo.YL_质量检验_质检记录.到货数, dbo.MES_接口_生产计划_生产任务.指派对象
FROM      dbo.YL_质量检验_质检记录 INNER JOIN
                dbo.MES_接口_生产计划_生产任务 ON 
                dbo.YL_质量检验_质检记录.TaskAID = dbo.MES_接口_生产计划_生产任务.AID
WHERE   (dbo.MES_接口_生产计划_生产任务.指派对象 = '外协') AND (dbo.YL_质量检验_质检记录.质检类型 = '收检')
GO
/****** Object:  View [dbo].[View_生产订单全部（包括已关闭）]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE VIEW [dbo].[View_生产订单全部（包括已关闭）]
AS
SELECT  a.订单编号, a.合同号, b.订单拆分内码, a.订单类型, a.订单状态, a.物料编号, a.物料描述, b.计划数量 AS 工序计划数量, a.计量单位, a.下达日期, 
               a.计划开始, a.计划完成, a.项目代码, a.备注, a.重量, a.占用情况, a.加急状态, a.同步时间, b.订单行号, b.物料编码, b.物料名称, b.基本数量, b.计划数量, 
               b.已发货数量, b.订单发货类型, b.仓库代码, b.可视订单, b.物料类型, b.阶段标识, b.工序名称, b.顺序编号, b.性质, b.总工时, b.行文本备注, b.不装配, 
               b.指派对象, b.指派数量, b.计划开始时间, b.计划完成时间, b.最晚开始时间, b.派工状态, b.派工时间, b.任务状态, b.修改时间, b.外协通知, b.优先级, 
               b.未完成说明, b.派工特殊说明, b.最后编辑人, b.最后编辑时间, b.可执行, b.收料, b.收料数量, b.开工, b.首检, b.巡检, b.完成数量, b.进度, b.序检, b.测试, 
               b.入库, b.AID AS TaskAID, b.加工状态, b.操作时间, b.开工时间, b.完工时间, b.合格数量, b.不合格数量, b.让步放行数量, b.报废数量, 
               a.计划数量 AS 计划数量订单, b.排产状态, a.自制件属性, b.二次派工, a.周转单打印次数, b.外协打印次数, b.单重, b.外协备注, a.齐套, a.单据状态, 
               a.生产工艺, a.标准工艺, a.任务状态 AS Expr1, b.指派对象编号, dbo.MES_资源主数据.VisCode, a.发料状态, a.拣配状态, a.计划号, b.外协分组, 
               a.加急数量, a.发货状态, a.要求发货日期, a.加急总数, b.打印数量, a.入库数量, dbo.物料基础数据_零件图纸.worker, b.本次检数
FROM     dbo.MES_接口_生产计划_生产任务 AS b LEFT OUTER JOIN
               dbo.物料基础数据_零件图纸 ON b.物料编码 = dbo.物料基础数据_零件图纸.num LEFT OUTER JOIN
               dbo.MES_资源主数据 ON b.指派对象 = dbo.MES_资源主数据.Name RIGHT OUTER JOIN
               dbo.MES_接口_生产计划 AS a ON b.订单编号 = a.订单编号
WHERE   (b.物料类型 = 'pit_Resource')
GO
/****** Object:  View [dbo].[View_外协质检]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE VIEW [dbo].[View_外协质检]
AS
SELECT  a.QT_AID, a.TaskAID, a.检测类型编号, a.质检类型, a.零件编码, a.零件名称, a.内部合同号, a.计划号, a.工序名称, a.计划生产数, a.检验数量, a.合格数, 
               a.不合格数, a.检测人, a.检测时间, a.检测说明, a.行号, a.订单类型, a.到货数, b.指派对象
FROM     dbo.YL_质量检验_质检记录 AS a LEFT OUTER JOIN
               dbo.MES_接口_生产计划_生产任务 AS b ON a.TaskAID = b.AID
WHERE   (b.指派对象 = '外协') AND (a.质检类型 = '收检')
GO
/****** Object:  View [dbo].[View_装配信息]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE VIEW [dbo].[View_装配信息]
AS
SELECT  MAX(a.完成数量) AS 送检数, SUM(b.合格数) AS 质检合格数, a.订单编号
FROM     dbo.MES_接口_生产计划_生产任务 AS a LEFT OUTER JOIN
               dbo.YL_质量检验_质检记录 AS b ON a.AID = b.TaskAID AND b.质检类型 = '收检'
WHERE   (a.指派对象 LIKE '%装配%')
GROUP BY a.订单编号
GO
/****** Object:  View [dbo].[View_生产计划零件图纸视图]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE VIEW [dbo].[View_生产计划零件图纸视图]
AS
SELECT  dbo.MES_接口_生产计划.AID, dbo.MES_接口_生产计划.订单编号, dbo.MES_接口_生产计划.合同号, dbo.MES_接口_生产计划.订单类型, 
               dbo.MES_接口_生产计划.订单状态, dbo.MES_接口_生产计划.物料编号, dbo.MES_接口_生产计划.物料描述, dbo.MES_接口_生产计划.计划数量, 
               dbo.MES_接口_生产计划.计量单位, dbo.MES_接口_生产计划.下达日期, dbo.MES_接口_生产计划.计划开始, dbo.MES_接口_生产计划.计划完成, 
               dbo.MES_接口_生产计划.项目代码, dbo.MES_接口_生产计划.备注, dbo.MES_接口_生产计划.重量, dbo.MES_接口_生产计划.占用情况, 
               dbo.MES_接口_生产计划.加急状态, dbo.MES_接口_生产计划.排产状态, dbo.MES_接口_生产计划.排产时间, dbo.MES_接口_生产计划.同步时间, 
               dbo.MES_接口_生产计划.任务状态, dbo.MES_接口_生产计划.标准工艺, dbo.MES_接口_生产计划.生产工艺, dbo.MES_接口_生产计划.齐套, 
               dbo.MES_接口_生产计划.自制件属性, dbo.MES_接口_生产计划.周转单打印次数, dbo.MES_接口_生产计划.单据状态, 
               dbo.MES_接口_生产计划.预计齐套时间, dbo.MES_接口_生产计划.发料状态, dbo.MES_接口_生产计划.拣配状态, dbo.MES_接口_生产计划.计划号, 
               dbo.MES_接口_生产计划.加急数量, dbo.MES_接口_生产计划.发货状态, dbo.MES_接口_生产计划.要求发货日期, dbo.MES_接口_生产计划.加急总数, 
               dbo.MES_接口_生产计划.入库数量, ISNULL(dbo.物料基础数据_零件图纸.worker, 0) AS worker
FROM     dbo.MES_接口_生产计划 LEFT OUTER JOIN
               dbo.物料基础数据_零件图纸 ON dbo.MES_接口_生产计划.物料编号 = dbo.物料基础数据_零件图纸.num
GO
/****** Object:  Table [dbo].[登录基础数据_角色信息]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[登录基础数据_角色信息](
	[Roles_number] [int] IDENTITY(1,1) NOT NULL,
	[Roles_Function] [nvarchar](50) NOT NULL,
 CONSTRAINT [PK_SCHAEFFLER_Roles_Table] PRIMARY KEY CLUSTERED 
(
	[Roles_number] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[登录基础数据_人员权限角色]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[登录基础数据_人员权限角色](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[Personnel_Number] [int] NOT NULL,
	[Roles_number] [int] NOT NULL,
 CONSTRAINT [PK_SCHAEFFLER_Permissionsroles] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[登录基础数据_二级菜单]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[登录基础数据_二级菜单](
	[IDD] [int] IDENTITY(1,1) NOT NULL,
	[id] [int] NULL,
	[pid] [int] NULL,
	[path] [varchar](100) NULL,
	[componet] [varchar](100) NULL,
	[redirect] [varchar](100) NULL,
	[name] [varchar](100) NULL,
	[title] [varchar](100) NULL,
	[icon] [varchar](100) NULL,
	[账号代码] [int] NULL,
	[模块代码] [int] NULL,
	[操作时间] [datetime] NULL,
	[是否启用] [int] NULL,
	[AddData] [int] NULL,
	[DeleteData] [int] NULL,
	[EditData] [int] NULL,
	[SearchData] [int] NULL,
 CONSTRAINT [PK_SCHAEFFLER_Menu_second] PRIMARY KEY CLUSTERED 
(
	[IDD] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  View [dbo].[View_账号权限信息]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE VIEW [dbo].[View_账号权限信息]
AS
SELECT  dbo.登录基础数据_人员信息.account AS Expr1, dbo.登录基础数据_人员信息.password, dbo.登录基础数据_人员信息.Personnel_Name, 
               dbo.登录基础数据_二级菜单.title, dbo.登录基础数据_角色信息.Roles_Function
FROM     dbo.登录基础数据_人员权限角色 INNER JOIN
               dbo.登录基础数据_角色信息 ON dbo.登录基础数据_人员权限角色.Roles_number = dbo.登录基础数据_角色信息.Roles_number INNER JOIN
               dbo.登录基础数据_人员信息 ON dbo.登录基础数据_人员权限角色.Personnel_Number = dbo.登录基础数据_人员信息.Personnel_Number INNER JOIN
               dbo.登录基础数据_二级菜单 ON dbo.登录基础数据_角色信息.Roles_number = dbo.登录基础数据_二级菜单.账号代码
GO
/****** Object:  Table [dbo].[车间生产管理工艺_零件工序_工艺库]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[车间生产管理工艺_零件工序_工艺库](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[零件图号] [nvarchar](100) NULL,
	[工艺编号] [int] NULL,
	[工艺顺序] [int] NULL,
	[工艺要求] [nvarchar](max) NULL,
	[是否最后一序] [tinyint] NULL,
	[计划数量] [int] NULL,
	[准备工时] [int] NULL,
	[标准工时] [int] NULL,
	[工时合计] [int] NULL,
	[工卡量具] [nvarchar](200) NULL,
	[指定机床] [nvarchar](200) NULL,
	[车间] [nvarchar](200) NULL,
	[备注] [nvarchar](500) NULL,
	[启用] [int] NOT NULL,
 CONSTRAINT [PK_MES_工艺管理_工艺路线] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object:  View [dbo].[计划任务视图]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE VIEW [dbo].[计划任务视图]
AS
SELECT  dbo.车间生产管理工艺_零件工序_工艺库.工艺编号, dbo.MES_接口_生产计划.订单编号, dbo.MES_接口_生产计划_生产任务.物料名称
FROM     dbo.MES_接口_生产计划 INNER JOIN
               dbo.MES_接口_生产计划_生产任务 ON dbo.MES_接口_生产计划.订单编号 = dbo.MES_接口_生产计划_生产任务.订单编号 INNER JOIN
               dbo.车间生产管理工艺_零件工序_工艺库 ON dbo.MES_接口_生产计划.订单编号 = dbo.车间生产管理工艺_零件工序_工艺库.订单编号
GO
/****** Object:  Table [dbo].[基础表_工序]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[基础表_工序](
	[AID] [int] IDENTITY(1,1) NOT NULL,
	[工艺编号] [int] NOT NULL,
	[工序名称] [nvarchar](50) NULL,
 CONSTRAINT [PK_基础表_工序] PRIMARY KEY CLUSTERED 
(
	[工艺编号] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  View [dbo].[View_标准工艺视图]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE VIEW [dbo].[View_标准工艺视图]
AS
SELECT  dbo.MES_接口_生产计划.物料描述 AS 零件名称, dbo.车间生产管理工艺_零件工序_工艺库.id, dbo.车间生产管理工艺_零件工序_工艺库.零件图号, 
               dbo.车间生产管理工艺_零件工序_工艺库.工艺编号, dbo.车间生产管理工艺_零件工序_工艺库.工艺顺序, 
               dbo.车间生产管理工艺_零件工序_工艺库.工艺要求, dbo.车间生产管理工艺_零件工序_工艺库.是否最后一序, 
               dbo.车间生产管理工艺_零件工序_工艺库.计划数量, dbo.车间生产管理工艺_零件工序_工艺库.准备工时, 
               dbo.车间生产管理工艺_零件工序_工艺库.标准工时, dbo.车间生产管理工艺_零件工序_工艺库.工时合计, 
               dbo.车间生产管理工艺_零件工序_工艺库.工卡量具, dbo.车间生产管理工艺_零件工序_工艺库.指定机床, 
               dbo.车间生产管理工艺_零件工序_工艺库.车间, dbo.车间生产管理工艺_零件工序_工艺库.备注, dbo.车间生产管理工艺_零件工序_工艺库.启用, 
               dbo.MES_接口_生产计划.标准工艺, dbo.基础表_工序.工序名称
FROM     dbo.基础表_工序 INNER JOIN
               dbo.车间生产管理工艺_零件工序_工艺库 ON dbo.基础表_工序.工艺编号 = dbo.车间生产管理工艺_零件工序_工艺库.工艺编号 RIGHT OUTER JOIN
               dbo.MES_接口_生产计划 ON dbo.车间生产管理工艺_零件工序_工艺库.零件图号 = dbo.MES_接口_生产计划.物料编号
GO
/****** Object:  Table [dbo].[车间生产管理工艺_零件生产工艺_工艺库]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[车间生产管理工艺_零件生产工艺_工艺库](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[零件图号] [nvarchar](100) NULL,
	[工艺编号] [int] NULL,
	[工艺顺序] [int] NULL,
	[工艺要求] [nvarchar](max) NULL,
	[是否最后一序] [tinyint] NULL,
	[订单编号] [int] NULL,
	[计划数量] [int] NULL,
	[准备工时] [int] NULL,
	[标准工时] [int] NULL,
	[工时合计] [int] NULL,
	[工卡量具] [nvarchar](200) NULL,
	[指定机床] [nvarchar](200) NULL,
	[车间] [nvarchar](200) NULL,
	[备注] [nvarchar](500) NULL,
	[启用] [int] NOT NULL,
	[属性] [nvarchar](200) NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object:  View [dbo].[View_生产工艺视图]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE VIEW [dbo].[View_生产工艺视图]
AS
SELECT  dbo.车间生产管理工艺_零件生产工艺_工艺库.id, dbo.车间生产管理工艺_零件生产工艺_工艺库.零件图号, 
               dbo.车间生产管理工艺_零件生产工艺_工艺库.工艺编号, dbo.车间生产管理工艺_零件生产工艺_工艺库.工艺顺序, 
               dbo.车间生产管理工艺_零件生产工艺_工艺库.工艺要求, dbo.车间生产管理工艺_零件生产工艺_工艺库.是否最后一序, 
               dbo.车间生产管理工艺_零件生产工艺_工艺库.订单编号, dbo.车间生产管理工艺_零件生产工艺_工艺库.计划数量, 
               dbo.车间生产管理工艺_零件生产工艺_工艺库.准备工时, dbo.车间生产管理工艺_零件生产工艺_工艺库.标准工时, 
               dbo.车间生产管理工艺_零件生产工艺_工艺库.工时合计, dbo.车间生产管理工艺_零件生产工艺_工艺库.工卡量具, 
               dbo.车间生产管理工艺_零件生产工艺_工艺库.指定机床, dbo.车间生产管理工艺_零件生产工艺_工艺库.车间, 
               dbo.车间生产管理工艺_零件生产工艺_工艺库.备注, dbo.车间生产管理工艺_零件生产工艺_工艺库.启用, 
               dbo.MES_接口_生产计划.物料描述 AS 零件名称, dbo.MES_接口_生产计划.生产工艺, dbo.MES_接口_生产计划.周转单打印次数, 
               dbo.MES_接口_生产计划.自制件属性, dbo.MES_接口_生产计划.任务状态, dbo.MES_接口_生产计划.计划号, dbo.MES_接口_生产计划.单据状态, 
               dbo.MES_接口_生产计划.拣配状态
FROM     dbo.车间生产管理工艺_零件生产工艺_工艺库 LEFT OUTER JOIN
               dbo.MES_接口_生产计划 ON dbo.车间生产管理工艺_零件生产工艺_工艺库.订单编号 = dbo.MES_接口_生产计划.订单编号
GO
/****** Object:  View [dbo].[View_报工人员]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE VIEW [dbo].[View_报工人员]
AS
SELECT  操作人
FROM     dbo.YL_加工中心_操作记录表
GROUP BY 操作人
GO
/****** Object:  Table [dbo].[班次表]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[班次表](
	[班次编号] [nvarchar](50) NOT NULL,
	[班次名称] [nvarchar](50) NOT NULL,
	[开始时间] [time](7) NOT NULL,
	[结束时间] [time](7) NOT NULL,
	[创建时间] [datetime] NOT NULL,
	[创建人] [nvarchar](50) NOT NULL,
	[更新时间] [datetime] NOT NULL,
	[更新人] [nvarchar](50) NOT NULL,
	[是否删除] [bit] NULL,
PRIMARY KEY CLUSTERED 
(
	[班次编号] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[班次人员绑定表]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[班次人员绑定表](
	[绑定ID] [int] IDENTITY(1,1) NOT NULL,
	[班次编号] [nvarchar](50) NOT NULL,
	[人员编号] [nvarchar](50) NOT NULL,
	[绑定时间] [datetime] NOT NULL,
	[创建时间] [datetime] NOT NULL,
	[创建人] [nvarchar](50) NOT NULL,
	[更新时间] [datetime] NOT NULL,
	[更新人] [nvarchar](50) NOT NULL,
	[是否删除] [bit] NULL,
PRIMARY KEY CLUSTERED 
(
	[绑定ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  View [dbo].[View_设备工位人员]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE VIEW [dbo].[View_设备工位人员]
AS
SELECT DISTINCT 
               dbo.登录基础数据_人员信息.Personnel_Name AS 人员名称, dbo.MES_资源主数据.Name AS 工位名称, dbo.班次人员绑定表.是否删除, 
               dbo.班次表.班次名称, dbo.班次表.开始时间, dbo.班次表.结束时间, dbo.工位人员绑定表.人员编号
FROM     dbo.登录基础数据_人员信息 INNER JOIN
               dbo.工位人员绑定表 ON dbo.登录基础数据_人员信息.Personnel_Number = dbo.工位人员绑定表.人员编号 INNER JOIN
               dbo.班次人员绑定表 ON dbo.登录基础数据_人员信息.Personnel_Number = dbo.班次人员绑定表.人员编号 INNER JOIN
               dbo.班次表 ON dbo.班次人员绑定表.班次编号 = dbo.班次表.班次编号 RIGHT OUTER JOIN
               dbo.MES_资源主数据 ON dbo.工位人员绑定表.工位号 = dbo.MES_资源主数据.VisCode
WHERE   (dbo.班次人员绑定表.是否删除 = 0) AND (dbo.工位人员绑定表.绑定状态 = 1)
GO
/****** Object:  Table [dbo].[YL_质量检验_不合格品处理]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[YL_质量检验_不合格品处理](
	[FlowAID] [int] IDENTITY(1,1) NOT NULL,
	[TaskAID] [int] NULL,
	[不合格数量] [int] NULL,
	[申请让步放行] [int] NULL,
	[申请内容] [nvarchar](2000) NULL,
	[发起人ID] [int] NULL,
	[发起时间] [datetime] NULL,
	[结束时间] [datetime] NULL,
 CONSTRAINT [PK_YL_质量检验_不合格品处理] PRIMARY KEY CLUSTERED 
(
	[FlowAID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[YL_质量检验_不合格品处理_处理节点]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[YL_质量检验_不合格品处理_处理节点](
	[AID] [int] IDENTITY(1,1) NOT NULL,
	[FlowAID] [int] NOT NULL,
	[FlowNodeID] [int] NOT NULL,
	[处理人ID] [int] NULL,
	[接收时间] [datetime] NULL,
	[完成时间] [datetime] NULL,
	[让步放行数量] [int] NULL,
	[处理意见] [nvarchar](2000) NULL,
 CONSTRAINT [PK_YL_质量检验_不合格品处理_处理节点] PRIMARY KEY CLUSTERED 
(
	[FlowAID] ASC,
	[FlowNodeID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  View [dbo].[View_质量检验_不合格品处理]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE VIEW [dbo].[View_质量检验_不合格品处理]
AS
SELECT   dbo.YL_质量检验_不合格品处理.FlowAID, dbo.YL_质量检验_不合格品处理.TaskAID, 
                dbo.YL_质量检验_不合格品处理.不合格数量, dbo.YL_质量检验_不合格品处理.申请让步放行, 
                dbo.YL_质量检验_不合格品处理.申请内容, dbo.YL_质量检验_不合格品处理.发起人ID, 
                dbo.YL_质量检验_不合格品处理.发起时间, dbo.YL_质量检验_不合格品处理.结束时间, 
                dbo.YL_质量检验_不合格品处理_处理节点.FlowNodeID, dbo.YL_质量检验_不合格品处理_处理节点.处理人ID, 
                dbo.YL_质量检验_不合格品处理_处理节点.接收时间, dbo.YL_质量检验_不合格品处理_处理节点.完成时间, 
                dbo.YL_质量检验_不合格品处理_处理节点.让步放行数量, dbo.YL_质量检验_不合格品处理_处理节点.处理意见
FROM      dbo.YL_质量检验_不合格品处理 INNER JOIN
                dbo.YL_质量检验_不合格品处理_处理节点 ON 
                dbo.YL_质量检验_不合格品处理.FlowAID = dbo.YL_质量检验_不合格品处理_处理节点.FlowAID
GO
/****** Object:  View [dbo].[View_校验后的生产工时]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE VIEW [dbo].[View_校验后的生产工时]
AS
SELECT  ISNULL(c.AID, o.AID) AS AID, ISNULL(c.操作类别编号, o.操作类别编号) AS 操作类别编号, ISNULL(c.操作类别, o.操作类别) AS 操作类别, 
               ISNULL(c.阶段标识, o.阶段标识) AS 阶段标识, ISNULL(c.工序名称, o.工序名称) AS 工序名称, ISNULL(c.工位编号, o.工位编号) AS 工位编号, 
               ISNULL(c.工位名称, o.工位名称) AS 工位名称, ISNULL(c.操作人, o.操作人) AS 操作人, ISNULL(c.合同号, o.合同号) AS 合同号, ISNULL(c.订单编号, 
               o.订单编号) AS 订单号, ISNULL(c.物料编号, o.物料编号) AS 产品编码, ISNULL(c.物料描述, o.物料描述) AS 产品名称, ISNULL(c.操作数值, o.操作数值) 
               AS 操作数值, ISNULL(c.操作内容, o.操作内容) AS 操作内容, ISNULL(c.操作描述, o.操作描述) AS 操作描述, ISNULL(c.TaskAID, o.TaskAID) AS TaskAID, 
               ISNULL(c.开始时间, o.开始时间) AS 开始时间, ISNULL(c.结束时间, o.结束时间) AS 结束时间, ISNULL(c.工时, o.实际工时) AS 加工工时, ISNULL(o.总时长, 
               0) AS 总时长, ISNULL(c.报工日期, o.报工日期) AS 报工日期, ISNULL(c.已报工, o.已报工) AS 已报工, ISNULL(c.不装配, o.不装配) AS 不装配, 
               CASE WHEN c.AID IS NOT NULL THEN 1 ELSE 0 END AS 已校验, ISNULL(c.最后编辑人, o.最后编辑人) AS 最后编辑人, ISNULL(c.最后编辑时间, 
               o.最后编辑时间) AS 最后编辑时间, m.订单行号, m.顺序编号, m.VisCode, c.AID AS Expr1, m.计划数量, m.完成数量, m.自制件属性, 
               s.合同号 AS 订单合同号
FROM     dbo.YL_加工中心_操作记录表 AS o LEFT OUTER JOIN
               dbo.生产管理_工时校验_校验工时表 AS c ON o.AID = c.报工记录id LEFT OUTER JOIN
               dbo.View_生产订单_MES AS m ON ISNULL(c.TaskAID, o.TaskAID) = m.TaskAID LEFT OUTER JOIN
               dbo.MES_接口_生产计划 AS s ON ISNULL(c.订单编号, o.订单编号) = s.订单编号
WHERE   (o.工位名称 <> '外协') AND (NOT (o.操作类别 = '报工') OR
               NOT (ISNULL(c.结束时间, o.结束时间) IS NULL)) AND (c.AID IS NOT NULL OR
               o.操作类别 <> '收料') AND (c.AID IS NOT NULL OR
               (NOT (o.操作内容 IN ('开始加工', '辅助开始')) OR
               NOT (o.结束时间 IS NULL) OR
               NOT EXISTS
                   (SELECT  1 AS Expr1
                   FROM     dbo.YL_加工中心_操作记录表 AS t2
                   WHERE   (操作内容 IN ('报工', '辅助结束')) AND (TaskAID = o.TaskAID) AND (开始时间 = o.开始时间))) AND (NOT (o.操作内容 IN ('辅助结束')) OR
               NOT EXISTS
                   (SELECT  1 AS Expr1
                   FROM     dbo.YL_加工中心_操作记录表 AS p
                   WHERE   (操作内容 = '辅助结束') AND (TaskAID = o.TaskAID) AND (结束时间 IS NULL))) AND (NOT (o.操作内容 IN ('开始加工', '辅助开始')) OR
               NOT EXISTS
                   (SELECT  1 AS Expr1
                   FROM     dbo.YL_加工中心_操作记录表 AS p
                   WHERE   (操作内容 = '暂停') AND (TaskAID = o.TaskAID) AND (结束时间 = o.开始时间) AND (操作人 = o.操作人))) AND (o.操作数值 IS NOT NULL OR
               o.操作内容 IN ('开始加工', '辅助开始') AND o.结束时间 IS NULL OR
               o.操作描述 <> '')) AND (c.AID IS NOT NULL)
GO
/****** Object:  Table [dbo].[登录基础数据_部门]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[登录基础数据_部门](
	[部门编号] [int] NOT NULL,
	[部门名称] [nvarchar](50) NULL,
	[操作日期] [datetime] NULL,
 CONSTRAINT [PK_基础表_部门] PRIMARY KEY CLUSTERED 
(
	[部门编号] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  View [dbo].[登录基础数据_管理人员权限视图]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE VIEW [dbo].[登录基础数据_管理人员权限视图]
AS
SELECT   dbo.登录基础数据_角色信息.Roles_number, dbo.登录基础数据_角色信息.Roles_Function, 
                dbo.登录基础数据_人员信息.Personnel_Number, dbo.登录基础数据_人员信息.account, 
                dbo.登录基础数据_人员信息.password, dbo.登录基础数据_人员信息.Personnel_Name, 
                dbo.登录基础数据_人员信息.Departments_ID, dbo.登录基础数据_人员信息.Quit, dbo.登录基础数据_部门.部门名称, 
                dbo.登录基础数据_人员信息.OrgUnit
FROM      dbo.登录基础数据_角色信息 INNER JOIN
                dbo.登录基础数据_人员权限角色 ON 
                dbo.登录基础数据_角色信息.Roles_number = dbo.登录基础数据_人员权限角色.Roles_number INNER JOIN
                dbo.登录基础数据_人员信息 ON 
                dbo.登录基础数据_人员权限角色.Personnel_Number = dbo.登录基础数据_人员信息.Personnel_Number LEFT OUTER JOIN
                dbo.登录基础数据_部门 ON dbo.登录基础数据_人员信息.OrgUnit = dbo.登录基础数据_部门.部门编号
GO
/****** Object:  View [dbo].[View_生产订单完工]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE VIEW [dbo].[View_生产订单完工]
AS
SELECT  v.订单号
FROM     dbo.View_生产工时视图 AS v LEFT OUTER JOIN
                   (SELECT  TaskAID, SUM(ISNULL(合格数, 0)) AS 合格数合计, SUM(ISNULL(不合格数, 0)) AS 不合格数合计
                   FROM     dbo.YL_质量检验_质检记录
                   WHERE   (质检类型 = '收检')
                   GROUP BY TaskAID) AS zj_收检 ON v.TaskAID = zj_收检.TaskAID LEFT OUTER JOIN
                   (SELECT  TaskAID, SUM(ISNULL(合格数, 0)) AS 终检合格数合计, SUM(ISNULL(不合格数, 0)) AS 终检不合格数合计
                   FROM     dbo.YL_质量检验_质检记录 AS YL_质量检验_质检记录_1
                   WHERE   (质检类型 = '终检')
                   GROUP BY TaskAID) AS zj_终检数量 ON v.TaskAID = zj_终检数量.TaskAID
WHERE   (v.加工工时 > 0) AND (v.Expr1 IS NOT NULL) AND (ISNULL(zj_终检数量.终检合格数合计, 0) + ISNULL(zj_终检数量.终检不合格数合计, 0) 
               + ISNULL(zj_收检.不合格数合计, 0) = v.计划数量) AND (ISNULL(v.入库数量, 0) = ISNULL(zj_终检数量.终检合格数合计, 0)) OR
               (v.Expr1 IS NOT NULL) AND (ISNULL(zj_终检数量.终检合格数合计, 0) + ISNULL(zj_终检数量.终检不合格数合计, 0) + ISNULL(zj_收检.不合格数合计, 0) 
               = v.计划数量) AND (ISNULL(v.入库数量, 0) = ISNULL(zj_终检数量.终检合格数合计, 0)) AND (v.总时长 > 0) OR
               (v.加工工时 > 0) AND (v.Expr1 IS NOT NULL) AND (ISNULL(zj_收检.不合格数合计, 0) = v.计划数量) OR
               (v.Expr1 IS NOT NULL) AND (v.总时长 > 0) AND (ISNULL(zj_收检.不合格数合计, 0) = v.计划数量)
GROUP BY v.订单号
GO
/****** Object:  View [dbo].[View_终检状态]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE VIEW [dbo].[View_终检状态]
AS
SELECT    计划号
FROM       dbo.YL_质量检验_质检记录
WHERE    (质检类型 = '终检')
GROUP BY 计划号
GO
/****** Object:  View [dbo].[View_质检明细]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE VIEW [dbo].[View_质检明细]
AS
SELECT  dbo.YL_质量检验_质检记录.质检类型, dbo.YL_质量检验_质检记录.零件编码, dbo.YL_质量检验_质检记录.零件名称, 
               dbo.YL_质量检验_质检记录.计划号, dbo.YL_质量检验_质检记录.工序名称, dbo.YL_质量检验_质检记录.检验数量, dbo.YL_质量检验_质检记录.合格数, 
               dbo.YL_质量检验_质检记录.不合格数, dbo.YL_质量检验_质检记录.检测人, dbo.YL_质量检验_质检记录.检测时间, 
               dbo.YL_质量检验_质检记录.检测说明, dbo.YL_质量检验_质检记录.订单类型, dbo.YL_质量检验_质检记录.放行数量, 
               dbo.MES_接口_生产计划_生产任务.指派对象 AS 工位名称, dbo.YL_质量检验_质检记录.QT_AID, dbo.MES_接口_生产计划.合同号 AS 内部合同号
FROM     dbo.YL_质量检验_质检记录 LEFT OUTER JOIN
               dbo.MES_接口_生产计划_生产任务 ON dbo.MES_接口_生产计划_生产任务.AID = dbo.YL_质量检验_质检记录.TaskAID LEFT OUTER JOIN
               dbo.MES_接口_生产计划 ON dbo.YL_质量检验_质检记录.计划号 = dbo.MES_接口_生产计划.订单编号
GO
/****** Object:  View [dbo].[View_外协报表视图]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE VIEW [dbo].[View_外协报表视图]
AS
SELECT  v.计划号, v.加急总数, v.拣配状态, v.自制件属性, v.入库数量, CASE WHEN ISNULL(v.任务状态, 0) = 4 THEN '已完成' WHEN ISNULL(v.任务状态, 0) 
               = 2 THEN '已开工' WHEN ISNULL(v.任务状态, 0) = 0 THEN '待执行' WHEN ISNULL(v.任务状态, 0) = 1 THEN '可执行' ELSE '' END AS 任务状态, 
               CASE WHEN ISNULL(v.加工状态, 0) = 2 THEN '辅助开始' WHEN ISNULL(v.加工状态, 0) = 3 THEN '辅助结束' WHEN ISNULL(v.加工状态, 0) 
               = 4 THEN '开始加工' WHEN ISNULL(v.加工状态, 0) = 5 THEN '暂停' WHEN ISNULL(v.加工状态, 0) = 6 THEN '报工' ELSE '' END AS 加工状态, 
               v.计划数量订单, ISNULL(v.进度, 0) AS 进度, v.TaskAID, v.合同号, v.订单编号 AS 订单号, v.订单行号, v.物料编号 AS 产品编码, v.物料描述 AS 产品名称, 
               CASE WHEN v.[计划数量] IS NULL THEN '' ELSE LTRIM(RTRIM(STR(v.[计划数量], 30, 0))) END AS 计划数量, v.计划完成 AS 要求完工日期, v.工序名称, 
               v.完成数量, v.收料数量, CASE WHEN v.[加急状态] = 1 THEN '加急' ELSE '' END AS 加急状态, v.加急数量, v.工序计划数量, v.指派对象, 
               CASE WHEN v.[指派数量] IS NULL THEN '' ELSE LTRIM(RTRIM(STR(v.[指派数量], 30, 0))) END AS 指派数量, v.计划开始时间, v.计划完成时间, 
               v.最晚开始时间, v.派工状态, v.优先级, v.未完成说明, v.派工特殊说明, v.最后编辑人, v.最后编辑时间, ISNULL(zj_收检.合格数合计, 0) AS 收检合格数, 
               ISNULL(zj_收检.不合格数合计, 0) AS 收检不合格数, ISNULL(zj_收检.合格数合计, 0) + ISNULL(zj_收检.不合格数合计, 0) AS 收检总数, ISNULL(jl.开始时间, 
               0) AS 开始时间, ISNULL(jl.结束时间, 0) AS 结束时间, ISNULL(jl.外协结束时间, 0) AS 外协结束时间, v.开工时间, v.订单拆分内码 AS 拆分内码, v.外协分组, 
               s.含税行总计, s.含税单价, s.未税行总计, s.未税单价, s.供应商名称, s.采购预计到货日期, s.开票数量, s.材质, ISNULL(fl.发料数量合计, 0) 
               AS 发料数量合计, ISNULL(sl.收料数量_报工, 0) AS 收料数量_报工
FROM     dbo.View_生产订单_MES AS v LEFT OUTER JOIN
                   (SELECT  TaskAID, SUM(ISNULL(合格数, 0)) AS 合格数合计, SUM(ISNULL(不合格数, 0)) AS 不合格数合计
                   FROM     dbo.YL_质量检验_质检记录
                   WHERE   (质检类型 = '收检')
                   GROUP BY TaskAID) AS zj_收检 ON v.TaskAID = zj_收检.TaskAID LEFT OUTER JOIN
                   (SELECT  TaskAID, MIN(ISNULL(开始时间, 0)) AS 开始时间, MAX(ISNULL(开始时间, 0)) AS 外协结束时间, MAX(ISNULL(结束时间, 0)) AS 结束时间
                   FROM     dbo.YL_加工中心_操作记录表
                   GROUP BY TaskAID) AS jl ON v.TaskAID = jl.TaskAID LEFT OUTER JOIN
               SAP.SBO_YL.dbo.UBT_WW_MES_OPORandOPCH AS s ON s.U_WWOrstID = v.TaskAID LEFT OUTER JOIN
                   (SELECT  TaskAID, SUM(ISNULL(操作数值, 0)) AS 发料数量合计
                   FROM     dbo.YL_加工中心_操作记录表 AS YL_加工中心_操作记录表_2
                   WHERE   (操作类别 = '收料')
                   GROUP BY TaskAID) AS fl ON v.TaskAID = fl.TaskAID LEFT OUTER JOIN
                   (SELECT  TaskAID, SUM(ISNULL(操作数值, 0)) AS 收料数量_报工
                   FROM     dbo.YL_加工中心_操作记录表 AS YL_加工中心_操作记录表_1
                   WHERE   (操作类别 = '报工') AND (工位名称 = '外协')
                   GROUP BY TaskAID) AS sl ON v.TaskAID = sl.TaskAID
WHERE   (v.物料类型 = 'pit_Resource') AND (v.指派对象 = '外协')
GO
/****** Object:  View [dbo].[View_质量检验_质检记录]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE VIEW [dbo].[View_质量检验_质检记录]
AS
SELECT   QT_AID AS Expr1, TaskAID AS Expr2, 检测类型编号 AS Expr3, 质检类型 AS Expr4, 零件编码 AS Expr5, 
                零件名称 AS Expr6, 内部合同号 AS Expr7, 计划号 AS Expr8, 工序名称 AS Expr9, 计划生产数 AS Expr10, 
                检验数量 AS Expr11, 合格数 AS Expr12, 不合格数 AS Expr13, 检测人 AS Expr14, 检测时间 AS Expr15, 
                检测说明 AS Expr16, 行号 AS Expr17, 订单类型 AS Expr18, QT_AID, TaskAID, 检测类型编号, 质检类型, 零件编码, 
                零件名称, 内部合同号, 计划号, 工序名称, 计划生产数, 检验数量, 合格数, 不合格数, 检测人, 检测时间, 检测说明, 行号, 
                订单类型, 到货数
FROM      dbo.YL_质量检验_质检记录
GO
/****** Object:  View [dbo].[v_CurrentProductionStatus]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE VIEW [dbo].[v_CurrentProductionStatus] AS
SELECT 
    TaskAID,
    订单号,
    合同号,
    加急总数,
    派工特殊说明,
    [订单拆分内码],
    [订单行号],
    [开工时间],
    零件编码,
    零件名称,
    [加急],
    [优先],
    [指派对象编号],
    指派对象,
    工序名称,
    [二次派工],
    [计划号],
    分配数,
    计划开始,
    计划完成,
    收料,
    完成数量,
    [齐套],
    [发料状态],
    [拣配状态],
    [任务状态],
    [加工状态],
    加工状态编号,
    收检合格数,
    收检不合格数,
    人员名称,
    [首检],
    [序检],
    上序已完成本序未开始,
    生产类型
FROM (
    -- 机加当前序
    SELECT 
        main.TaskAID,
        main.[订单编号] as 订单号,
        main.合同号,
        main.加急总数,
        main.派工特殊说明,
        main.[订单拆分内码],
        main.[订单行号],
        main.[开工时间],
        main.[物料编号] as 零件编码,
        main.[物料描述] as 零件名称,
        CASE WHEN ISNULL(main.[加急状态],0)=1 THEN '加急' ELSE '否' END as [加急],
        main.[优先级] as [优先],
        main.[指派对象编号],
        main.指派对象,
        main.[工序名称],
        main.[二次派工],
        main.[计划号],
        ISNULL(main.[指派数量],0) as 分配数,
        main.[计划开始时间] as 计划开始,
        main.[计划完成时间] as 计划完成,
        ISNULL(main.[收料数量],0) as 收料,
        ISNULL(main.[完成数量],0) as 完成数量,
        CASE WHEN ISNULL(main.齐套,0)=1 THEN '是' ELSE '否' END as [齐套],
        CASE 
            WHEN ISNULL(main.发料状态,0)=1 THEN '发料齐套' 
            WHEN ISNULL(main.发料状态,0)=2 THEN '发料缺件'
            ELSE NULL
        END as [发料状态],
        CASE 
            WHEN ISNULL(main.拣配状态,0)=1 THEN '已拣配' 
            WHEN ISNULL(main.拣配状态,0)=0 THEN '未拣配'
            ELSE NULL
        END as [拣配状态],
        CASE 
            WHEN ISNULL(main.任务状态,0)=4 THEN '已完成' 
            WHEN ISNULL(main.任务状态,0)=2 THEN '已开工' 
            WHEN ISNULL(main.任务状态,0)=0 THEN '待执行' 
            WHEN ISNULL(main.任务状态,0)=1 THEN '可执行'
            ELSE '' 
        END as [任务状态],
        CASE 
            WHEN ISNULL(main.加工状态,0)=2 THEN '辅助开始'
            WHEN ISNULL(main.加工状态,0)=3 THEN '辅助结束'
            WHEN ISNULL(main.加工状态,0)=4 THEN '开始加工'
            WHEN ISNULL(main.加工状态,0)=5 THEN '暂停'
            WHEN ISNULL(main.加工状态,0)=6 THEN '报工'
            ELSE '' 
        END as [加工状态],
        ISNULL(main.加工状态,0) as 加工状态编号,
        ISNULL(zj_收检.合格数合计, 0) AS 收检合格数,
        ISNULL(zj_收检.不合格数合计, 0) AS 收检不合格数,
        STUFF((
            SELECT ',' + d2.人员名称
            FROM [dbo].[View_设备工位人员] d2
            WHERE d2.工位名称 = main.指派对象
            FOR XML PATH('')
        ), 1, 1, '') AS 人员名称,
        CASE WHEN ISNULL(main.[首检],-1)=1 THEN 'OK' WHEN ISNULL(main.[首检],-1)=0 THEN 'NG' ELSE '' END as [首检],
        CASE WHEN ISNULL(main.[序检],-1)=1 THEN 'OK' WHEN ISNULL(main.[序检],-1)=0 THEN 'NG' ELSE '' END as [序检],
        CASE 
            WHEN ISNULL(sq.上序总检验数量, 0) >= ISNULL(main.[指派数量], 0) 
                 AND (main.任务状态 NOT IN (1, 2) OR main.加工状态 NOT IN (2, 4))
            THEN '是'
            ELSE '否'
        END AS 上序已完成本序未开始,
        '机加' AS 生产类型,
        ROW_NUMBER() OVER (PARTITION BY main.[订单编号] ORDER BY main.[订单行号] DESC) AS rn
    FROM [View_生产订单_MES] AS main 
    LEFT JOIN (
        SELECT 
            TaskAID,
            SUM(ISNULL(合格数, 0)) AS 合格数合计,
            SUM(ISNULL(不合格数, 0)) AS 不合格数合计
        FROM dbo.YL_质量检验_质检记录
        WHERE 质检类型 = '收检'
        GROUP BY TaskAID
    ) zj_收检 ON main.TaskAID = zj_收检.TaskAID
    LEFT JOIN (
        SELECT 
            b.订单编号,
            b.订单行号,
            SUM(ISNULL(a.合格数, 0) + ISNULL(a.不合格数, 0)) AS 上序总检验数量
        FROM dbo.YL_质量检验_质检记录 a
        INNER JOIN [dbo].[MES_接口_生产计划_生产任务] b ON a.TaskAID = b.AID
        WHERE a.质检类型 = '收检'
        GROUP BY b.订单编号, b.订单行号
    ) sq ON main.[订单编号] = sq.订单编号 AND main.[订单行号] - 1 = sq.订单行号
    WHERE ISNULL(main.加工状态,0) in (2,4) AND ISNULL(main.任务状态,0) in (1,2)
    
    UNION ALL
    
    -- 装配当前序
    SELECT 
        t.TaskAID,
        t.订单编号 AS 订单号,
        NULL AS 合同号,
        NULL AS 加急总数,
        NULL AS 派工特殊说明,
        NULL AS [订单拆分内码],
        NULL AS [订单行号],
        t.开始时间 AS [开工时间],
        t.物料编号 AS 零件编码,
        t.物料描述 AS 零件名称,
        NULL AS [加急],
        NULL AS [优先],
        NULL AS [指派对象编号],
        t.工位名称 AS 指派对象,
        t.工序名称,
        NULL AS [二次派工],
        NULL AS [计划号],
        pt.指派数量 AS 分配数,
        pt.计划开始时间 AS 计划开始,
        pt.计划完成时间 AS 计划完成,
        NULL AS 收料,
        pt.完成数量,
        NULL AS [齐套],
        NULL AS [发料状态],
        NULL AS [拣配状态],
        CASE 
            WHEN ISNULL(pt.任务状态,0)=4 THEN '已完成' 
            WHEN ISNULL(pt.任务状态,0)=2 THEN '已开工' 
            WHEN ISNULL(pt.任务状态,0)=0 THEN '待执行' 
            WHEN ISNULL(pt.任务状态,0)=1 THEN '可执行'
            ELSE '' 
        END as [任务状态],
        '装配加工' AS [加工状态],
        4 AS 加工状态编号,
        NULL AS 收检合格数,
        NULL AS 收检不合格数,
        t.操作人 AS 人员名称,
        NULL AS [首检],
        NULL AS [序检],
        NULL AS 上序已完成本序未开始,
        '装配' AS 生产类型,
        1 AS rn
    FROM [dbo].[YL_加工中心_操作记录表] t
    LEFT JOIN [dbo].[MES_接口_生产计划_生产任务] pt ON t.TaskAID = pt.AID
    WHERE 
        t.操作类别 = '开始加工'
        AND t.结束时间 IS NULL
        AND t.工位名称 LIKE '%装配%'
        AND t.操作数值 IS NOT NULL
) AS Combined
WHERE rn = 1;
GO
/****** Object:  View [dbo].[View_生产订单Temp_ERP]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE VIEW [dbo].[View_生产订单Temp_ERP]
AS
SELECT   dbo.OWOR.AbsoluteEntry AS 订单编号, dbo.OWOR.ItemNo AS 物料编号, dbo.OWOR.ProductDescription AS 物料描述, 
                dbo.OWOR.ProductionOrderStatus AS 订单状态, dbo.OWOR.ProductionOrderType AS 订单类型, 
                dbo.OWOR.PlannedQuantity AS 计划数量, dbo.OWOR.PostingDate AS 下达日期, dbo.OWOR.StartDate AS 计划开始, 
                dbo.OWOR.DueDate AS 计划完成, dbo.OWOR.UoMEntry AS 计量单位, dbo.OWOR.Project AS 项目代码, 
                dbo.OWR1.LineNumber AS 订单行号, dbo.OWR1.ItemNo AS 物料编码, dbo.OWR1.ItemName AS 物料名称, 
                dbo.OWR1.BaseQuantity AS 基本数量, dbo.OWR1.PlannedQuantity, dbo.OWR1.IssuedQuantity AS 已发货数量, 
                dbo.OWR1.Warehouse AS 仓库代码, dbo.OWR1.VisualOrder AS 可视订单, dbo.OWR1.ItemType AS 物料类型, 
                dbo.OWR1.StageID AS 阶段标识, dbo.OWR1.LineText AS 行文本备注, dbo.OWR4.SequenceNumber AS 顺序编号, 
                dbo.OWR4.StageEntry AS 阶段条目, dbo.OWR4.Name AS 阶段名称, dbo.OWR4.StartDate AS 开始时间___, 
                dbo.OWR4.EndDate AS 结束时间____
FROM      dbo.OWOR LEFT OUTER JOIN
                dbo.OWR1 ON dbo.OWOR.AbsoluteEntry = dbo.OWR1.DocumentAbsoluteEntry LEFT OUTER JOIN
                dbo.OWR4 ON dbo.OWR1.DocumentAbsoluteEntry = dbo.OWR4.DocEntry AND dbo.OWR1.StageID = dbo.OWR4.StageID
GO
/****** Object:  Table [dbo].[_日志]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[_日志](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[UserID] [nvarchar](50) NULL,
	[主模块编号] [nvarchar](50) NULL,
	[子组件] [nvarchar](50) NULL,
	[标题] [nvarchar](50) NULL,
	[TypeID] [nvarchar](50) NULL,
	[名称] [nvarchar](200) NULL,
	[参数] [nvarchar](max) NULL,
	[日期] [date] NULL,
	[操作日期] [datetime] NULL,
 CONSTRAINT [PK__日志] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object:  Table [dbo].[Attachments]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Attachments](
	[AttachmentID] [int] IDENTITY(1,1) NOT NULL,
	[ProcessID] [int] NOT NULL,
	[FileName] [nvarchar](200) NOT NULL,
	[FilePath] [nvarchar](500) NOT NULL,
	[FileSize] [bigint] NULL,
	[FileType] [nvarchar](50) NULL,
	[UploaderID] [nvarchar](100) NOT NULL,
	[UploaderName] [nvarchar](100) NOT NULL,
	[UploadTime] [datetime] NULL,
	[Description] [nvarchar](500) NULL,
	[IsDeleted] [bit] NULL,
PRIMARY KEY CLUSTERED 
(
	[AttachmentID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[BOM数据]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[BOM数据](
	[编码] [nvarchar](max) NULL,
	[名称] [nvarchar](max) NULL,
	[ItmsGrpNam] [nvarchar](50) NULL,
	[数量] [tinyint] NULL,
	[入库仓库] [nvarchar](50) NULL,
	[子件编码] [nvarchar](max) NULL,
	[子件名称] [nvarchar](max) NULL,
	[子件数量] [float] NULL,
	[单位] [nvarchar](50) NULL,
	[子件出库仓库] [nvarchar](50) NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object:  Table [dbo].[CaChe_Var]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[CaChe_Var](
	[AID] [int] IDENTITY(1,1) NOT NULL,
	[CreateTime] [datetime] NULL,
	[UpdateTime] [datetime] NULL,
	[Zone] [nvarchar](50) NULL,
	[Sort] [int] NULL,
	[TagID] [nvarchar](50) NULL,
	[TagName] [nvarchar](200) NULL,
	[TagValue] [nvarchar](200) NULL,
	[TagUnit] [nvarchar](50) NULL,
	[TagValueOriginal] [nvarchar](200) NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[MES_接口_工艺路线主数据]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[MES_接口_工艺路线主数据](
	[AID] [int] IDENTITY(1,1) NOT NULL,
	[编号] [int] NULL,
	[代码] [nvarchar](50) NULL,
	[描述] [nvarchar](500) NULL,
	[装配类型] [nvarchar](50) NULL,
	[创建日期] [datetime] NULL,
	[生成时间] [nvarchar](50) NULL,
	[更新日期] [datetime] NULL,
	[同步时间] [datetime] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[YL_基础表_数据字典]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[YL_基础表_数据字典](
	[AID] [int] IDENTITY(1,1) NOT NULL,
	[词条编号] [int] NULL,
	[词条名称] [nvarchar](50) NULL,
	[数据类别] [nvarchar](50) NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[YL_加工中心_报工记录]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[YL_加工中心_报工记录](
	[AID] [int] IDENTITY(1,1) NOT NULL,
	[报工日期] [date] NULL,
	[班次] [nvarchar](50) NULL,
	[工位编号] [nvarchar](50) NULL,
	[工位名称] [nvarchar](50) NULL,
	[操作人] [nvarchar](50) NULL,
	[工时类型] [nvarchar](50) NULL,
	[报工数量] [int] NULL,
	[工时] [int] NULL,
	[确认工时] [int] NULL,
	[报工说明] [nvarchar](2000) NULL,
	[合同号] [nvarchar](50) NULL,
	[订单编号] [int] NULL,
	[TaskAID] [bigint] NULL,
	[TaskAID_Binding] [nvarchar](500) NULL,
	[报工时间] [datetime] NULL,
	[已确认] [int] NULL,
	[确认人] [nvarchar](50) NULL,
	[确认时间] [datetime] NULL,
	[已上报] [int] NULL,
	[上报时间] [datetime] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[YL_设备管理_工时记录]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[YL_设备管理_工时记录](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[指派对象] [nvarchar](50) NULL,
	[订单编号] [nchar](10) NULL,
	[循环时间] [int] NULL,
	[采集时间] [datetime] NULL,
	[TaskAID] [nchar](10) NULL,
 CONSTRAINT [PK_YL_设备管理_工时记录] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[YL_设备管理_设备台账]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[YL_设备管理_设备台账](
	[设备ID] [int] NOT NULL,
	[设备编号] [nvarchar](50) NULL,
	[设备名称] [nvarchar](100) NULL,
	[型号规格] [nvarchar](100) NULL,
	[制造商] [nvarchar](100) NULL,
	[所属车间] [nvarchar](50) NULL,
	[安装日期] [date] NULL,
	[预期寿命] [int] NULL,
	[状态] [int] NULL,
	[最后维护日期] [datetime] NULL,
	[责任人] [nvarchar](50) NULL,
	[技术参数JSON] [nvarchar](max) NULL,
PRIMARY KEY CLUSTERED 
(
	[设备ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY],
UNIQUE NONCLUSTERED 
(
	[设备编号] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object:  Table [dbo].[YL_设备管理_维修记录]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[YL_设备管理_维修记录](
	[AID] [int] IDENTITY(1,1) NOT NULL,
	[工位编号] [nvarchar](50) NULL,
	[工位名称] [nvarchar](50) NULL,
	[设备编号] [nvarchar](50) NULL,
	[设备名称] [nvarchar](50) NULL,
	[设备规格型号] [nvarchar](50) NULL,
	[故障描述] [nvarchar](2000) NULL,
	[故障时间] [datetime] NULL,
	[维修人员] [nvarchar](50) NULL,
	[维修完成时间] [datetime] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[YL_质量检验_检测标准]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[YL_质量检验_检测标准](
	[AID] [int] IDENTITY(1,1) NOT NULL,
	[物料编号] [nvarchar](500) NULL,
	[工序名称编号] [int] NULL,
	[检测项目] [nvarchar](2000) NULL,
	[理论值] [nvarchar](50) NULL,
	[上限值] [nvarchar](50) NULL,
	[下限值] [nvarchar](50) NULL,
	[测量单位] [nvarchar](50) NULL,
	[检验比例] [nvarchar](50) NULL,
	[检具] [nvarchar](50) NULL,
	[备注] [nvarchar](200) NULL,
	[检测类别编号] [int] NULL,
	[创建时间] [datetime] NULL,
	[更新时间] [datetime] NULL,
 CONSTRAINT [PK_YL_质量检验_检测标准] PRIMARY KEY CLUSTERED 
(
	[AID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[YL_质量检验_量具信息]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[YL_质量检验_量具信息](
	[AID] [int] IDENTITY(1,1) NOT NULL,
	[量具编号] [nvarchar](100) NULL,
	[量具名称] [nvarchar](100) NULL,
	[规格型号] [nvarchar](100) NULL,
	[制造商] [nvarchar](100) NULL,
	[精度等级] [nvarchar](100) NULL,
	[测量范围] [nvarchar](100) NULL,
	[量具状态] [nvarchar](100) NULL,
	[负责人] [nvarchar](100) NULL,
	[使用寿命] [nvarchar](100) NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[YL_质量检验_质检记录_检测零件]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[YL_质量检验_质检记录_检测零件](
	[LJ_AID] [bigint] IDENTITY(1,1) NOT NULL,
	[QT_AID] [bigint] NULL,
	[当前检测零件编号] [int] NULL,
	[检测结果] [nvarchar](500) NULL,
	[检测时间] [datetime] NULL,
	[检测人] [nvarchar](50) NULL,
	[零件编号] [nvarchar](50) NULL,
 CONSTRAINT [PK_YL_质量检验_质检记录_检测零件] PRIMARY KEY CLUSTERED 
(
	[LJ_AID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[YL_质量检验_质检记录_检测数据]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[YL_质量检验_质检记录_检测数据](
	[AID] [bigint] IDENTITY(1,1) NOT NULL,
	[LJ_AID] [bigint] NULL,
	[物料编号] [nvarchar](100) NULL,
	[当前检测零件编号] [int] NULL,
	[阶段标识] [int] NULL,
	[工序名称] [nvarchar](100) NULL,
	[计划号] [int] NULL,
	[检测项目] [nvarchar](500) NULL,
	[理论值] [nvarchar](50) NULL,
	[上限值] [nvarchar](50) NULL,
	[下限值] [nvarchar](50) NULL,
	[实测值] [nvarchar](50) NULL,
	[测量单位] [nvarchar](50) NULL,
	[检验比例] [nvarchar](50) NULL,
	[检具] [nvarchar](50) NULL,
	[检测结果] [int] NULL,
	[合格数] [int] NULL,
	[不合格数] [int] NULL,
	[备注] [nvarchar](200) NULL,
	[检测人] [nvarchar](50) NULL,
	[检测时间] [datetime] NULL,
 CONSTRAINT [PK_YL_质量检验_质检记录_检测数据] PRIMARY KEY CLUSTERED 
(
	[AID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[报警_记录_历史]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[报警_记录_历史](
	[AID] [int] IDENTITY(1,1) NOT NULL,
	[报警代码] [int] NULL,
	[报警内容] [nvarchar](2048) NULL,
	[开始时间] [datetime] NULL,
	[结束时间] [datetime] NULL,
	[持续时间] [int] NULL,
	[TagID] [nvarchar](2048) NULL,
	[工位号] [nvarchar](2048) NULL,
	[报警1提示2] [int] NULL,
	[报警级别] [nvarchar](2048) NULL,
 CONSTRAINT [PK_报警_记录_历史] PRIMARY KEY CLUSTERED 
(
	[AID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[报警_记录_历史_缓存]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[报警_记录_历史_缓存](
	[AID] [int] IDENTITY(1,1) NOT NULL,
	[报警代码] [int] NULL,
	[报警内容] [nvarchar](2048) NULL,
	[开始时间] [datetime] NULL,
	[结束时间] [datetime] NULL,
	[持续时间] [int] NULL,
	[TagID] [nvarchar](2048) NULL,
	[工位号] [nvarchar](2048) NULL,
	[报警级别] [nvarchar](2048) NULL,
 CONSTRAINT [PK_报警_记录_历史_缓存] PRIMARY KEY CLUSTERED 
(
	[AID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[基础数据_设备工位点检表]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[基础数据_设备工位点检表](
	[设备流水号] [int] IDENTITY(1,1) NOT NULL,
	[设备名称] [nvarchar](50) NULL,
	[设备型号] [nvarchar](50) NULL,
	[制造厂家] [nvarchar](100) NULL,
	[工位号] [nvarchar](50) NULL,
	[点检表类型] [int] NULL,
	[操作日期] [datetime] NULL,
	[保养人员代码] [int] NULL,
	[监督人员代码] [int] NULL,
	[设备类型] [nvarchar](50) NULL,
 CONSTRAINT [PK_基础数据_设备工位点检表] PRIMARY KEY CLUSTERED 
(
	[设备流水号] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[记录_日志_项目运行日志]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[记录_日志_项目运行日志](
	[AID] [bigint] IDENTITY(1,1) NOT NULL,
	[工位号] [nvarchar](2048) NULL,
	[日志类型] [nvarchar](2048) NULL,
	[TaskID] [nvarchar](2048) NULL,
	[请求CMD] [nvarchar](2048) NULL,
	[请求FROM] [nvarchar](2048) NULL,
	[请求TO] [nvarchar](2048) NULL,
	[请求时间] [datetime] NULL,
	[请求内容] [nvarchar](max) NULL,
	[响应时间] [datetime] NULL,
	[响应内容] [nvarchar](max) NULL,
	[请求内容安全] [nvarchar](max) NULL,
 CONSTRAINT [PK_记录_日志_项目运行日志] PRIMARY KEY CLUSTERED 
(
	[AID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object:  Table [dbo].[历史_工位设备状态每分钟记录]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[历史_工位设备状态每分钟记录](
	[AID_N] [bigint] IDENTITY(1,1) NOT NULL,
	[AID] [int] NULL,
	[DeviceCode] [nvarchar](50) NULL,
	[工位号] [nvarchar](2048) NULL,
	[订单号] [nvarchar](2048) NULL,
	[产品型号] [nvarchar](2048) NULL,
	[工号] [nvarchar](2048) NULL,
	[零件号] [nvarchar](2048) NULL,
	[设备状态] [int] NULL,
	[电流1] [real] NULL,
	[电流2] [real] NULL,
	[电流3] [real] NULL,
	[线电压1] [real] NULL,
	[线电压2] [real] NULL,
	[线电压3] [real] NULL,
	[功率1] [real] NULL,
	[功率2] [real] NULL,
	[功率3] [real] NULL,
	[总功率] [real] NULL,
	[电能] [real] NULL,
	[创建时间] [datetime] NULL,
	[自动模式] [int] NULL,
	[LineName] [nvarchar](200) NULL,
	[SyncTime] [datetime] NULL,
 CONSTRAINT [PK_历史_工位设备状态每分钟记录] PRIMARY KEY CLUSTERED 
(
	[AID_N] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[历史_设备数据_定时]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[历史_设备数据_定时](
	[AID] [bigint] IDENTITY(1,1) NOT NULL,
	[在线状态] [int] NULL,
	[创建时间] [datetime] NULL,
	[设备代码] [nvarchar](50) NULL,
	[工位号] [nvarchar](50) NULL,
	[变量类型代码] [int] NULL,
	[变量名称] [nvarchar](50) NULL,
	[值] [nvarchar](50) NULL,
	[TagID] [nvarchar](50) NULL,
	[DeviceCode] [nvarchar](200) NULL,
	[单位] [nvarchar](200) NULL,
	[原始值] [nvarchar](50) NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[流程表]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[流程表](
	[流程ID] [int] IDENTITY(1,1) NOT NULL,
	[流程标题] [nvarchar](200) NOT NULL,
	[流程描述] [nvarchar](max) NULL,
	[优先级] [nvarchar](20) NULL,
	[状态] [nvarchar](20) NULL,
	[发起人ID] [nvarchar](100) NOT NULL,
	[发起人姓名] [nvarchar](100) NOT NULL,
	[当前节点] [nvarchar](100) NULL,
	[当前步骤] [int] NULL,
	[总步骤数] [int] NULL,
	[截止时间] [datetime] NULL,
	[创建时间] [datetime] NULL,
	[更新时间] [datetime] NULL,
	[完成人] [nvarchar](100) NULL,
	[完成时间] [datetime] NULL,
	[完成原因] [nvarchar](500) NULL,
	[完成类型] [nvarchar](20) NULL,
	[已关联计划号] [int] NULL,
	[零件名称] [nvarchar](100) NULL,
	[零件编号] [nvarchar](100) NULL,
	[工序名称] [nvarchar](100) NULL,
	[num] [nvarchar](100) NULL,
	[uid] [nvarchar](100) NULL,
PRIMARY KEY CLUSTERED 
(
	[流程ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object:  Table [dbo].[流程节点表]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[流程节点表](
	[节点ID] [int] IDENTITY(1,1) NOT NULL,
	[流程ID] [int] NOT NULL,
	[节点名称] [nvarchar](100) NOT NULL,
	[审批人ID] [nvarchar](100) NULL,
	[审批人姓名] [nvarchar](100) NULL,
	[步骤序号] [int] NOT NULL,
	[状态] [nvarchar](20) NULL,
	[截止时间] [datetime] NULL,
	[创建时间] [datetime] NULL,
	[更新时间] [datetime] NULL,
	[是否转办] [bit] NULL,
	[转办ID] [int] NULL,
PRIMARY KEY CLUSTERED 
(
	[节点ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[流程完成记录表]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[流程完成记录表](
	[完成记录ID] [int] IDENTITY(1,1) NOT NULL,
	[流程ID] [int] NOT NULL,
	[发起人ID] [nvarchar](100) NOT NULL,
	[发起人姓名] [nvarchar](100) NOT NULL,
	[完成类型] [nvarchar](20) NOT NULL,
	[完成原因] [nvarchar](500) NULL,
	[完成时间] [datetime] NULL,
PRIMARY KEY CLUSTERED 
(
	[完成记录ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[流程转办表]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[流程转办表](
	[转办ID] [int] IDENTITY(1,1) NOT NULL,
	[流程ID] [int] NOT NULL,
	[原节点ID] [int] NOT NULL,
	[原审批人ID] [nvarchar](100) NOT NULL,
	[原审批人姓名] [nvarchar](100) NOT NULL,
	[新审批人ID] [nvarchar](100) NOT NULL,
	[新审批人姓名] [nvarchar](100) NOT NULL,
	[转办原因] [nvarchar](500) NULL,
	[转办时间] [datetime] NULL,
	[状态] [nvarchar](20) NULL,
PRIMARY KEY CLUSTERED 
(
	[转办ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[设备信息缓存表]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[设备信息缓存表](
	[指派对象] [nvarchar](50) NULL,
	[订单编号] [int] NULL,
	[合同号] [nvarchar](50) NULL,
	[计划号] [nvarchar](50) NULL,
	[物料名称] [nvarchar](500) NULL,
	[物料编码] [nvarchar](500) NULL,
	[订单行号] [int] NULL,
	[工序名称] [nvarchar](50) NULL,
	[指派数量] [decimal](16, 2) NULL,
	[加急总数] [decimal](19, 6) NULL,
	[完成数量] [int] NULL,
	[计划开始时间] [datetime] NULL,
	[计划完成时间] [datetime] NULL,
	[派工特殊说明] [nvarchar](500) NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[审批记录表]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[审批记录表](
	[记录ID] [int] IDENTITY(1,1) NOT NULL,
	[流程ID] [int] NOT NULL,
	[节点ID] [int] NOT NULL,
	[审批人ID] [nvarchar](100) NOT NULL,
	[审批人姓名] [nvarchar](100) NOT NULL,
	[处理结果] [nvarchar](20) NOT NULL,
	[审批意见] [nvarchar](max) NULL,
	[处理时间] [datetime] NULL,
PRIMARY KEY CLUSTERED 
(
	[记录ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object:  Table [dbo].[物料基础数据_工艺图纸]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[物料基础数据_工艺图纸](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[num] [nvarchar](100) NOT NULL,
	[uid] [nvarchar](100) NULL,
	[name] [nvarchar](100) NULL,
	[suffix] [nvarchar](50) NULL,
	[是否启用] [int] NULL,
	[worker] [nvarchar](100) NULL,
	[uploadTime] [nvarchar](100) NULL,
 CONSTRAINT [PK_物料基础数据_工艺图纸] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[物料基础数据_零件图纸删除记录]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[物料基础数据_零件图纸删除记录](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[物料编号] [nvarchar](100) NOT NULL,
	[文件名称] [nvarchar](255) NULL,
	[操作人] [nvarchar](50) NOT NULL,
	[删除时间] [datetime] NULL,
	[备注] [nvarchar](500) NULL,
PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[物料数据]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[物料数据](
	[物料编码] [nvarchar](max) NULL,
	[物料描述] [nvarchar](max) NULL,
	[物料分类] [nvarchar](max) NULL,
	[物料品牌] [nvarchar](50) NULL,
	[规格型号] [nvarchar](max) NULL,
	[是否可用] [nvarchar](50) NULL,
	[物料组] [nvarchar](50) NULL,
	[默认仓库] [nvarchar](50) NULL,
	[库存单位] [nvarchar](50) NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object:  Table [dbo].[质量检验_质检任务_SAP]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[质量检验_质检任务_SAP](
	[AID] [int] IDENTITY(1,1) NOT NULL,
	[订单编号] [int] NOT NULL,
	[物料名称] [nvarchar](500) NULL,
	[物料编码] [nvarchar](500) NULL,
	[入库数量] [decimal](18, 4) NULL,
	[检验结果] [nvarchar](50) NULL,
	[检测人] [nvarchar](50) NULL,
	[检验时间] [datetime] NULL,
	[合格数] [decimal](18, 4) NULL,
	[不合格数] [decimal](18, 4) NULL,
	[订单类型] [nvarchar](50) NULL,
	[同步时间] [datetime] NOT NULL,
	[行号] [int] NULL,
	[到货数] [decimal](18, 4) NULL,
	[采购到货时间] [nvarchar](50) NULL,
	[单据码] [nvarchar](50) NULL,
	[优先级] [nvarchar](50) NULL,
	[任务码] [nvarchar](50) NULL,
	[批次信息] [nvarchar](50) NULL,
	[存放位置] [nvarchar](50) NULL,
	[备注] [nvarchar](50) NULL,
	[加急状态] [int] NULL,
	[加急总数] [decimal](19, 6) NULL,
 CONSTRAINT [PK_质量检验_质检任务_SAP] PRIMARY KEY CLUSTERED 
(
	[AID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING ON
GO
/****** Object:  Index [IX_YL_加工中心_操作记录表_TaskAID_操作内容]    Script Date: 2026/5/18 8:58:57 ******/
CREATE NONCLUSTERED INDEX [IX_YL_加工中心_操作记录表_TaskAID_操作内容] ON [dbo].[YL_加工中心_操作记录表]
(
	[TaskAID] ASC,
	[操作内容] ASC,
	[开始时间] ASC,
	[结束时间] ASC,
	[操作人] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
SET ANSI_PADDING ON
GO
/****** Object:  Index [IX_工位人员绑定表_工位号]    Script Date: 2026/5/18 8:58:57 ******/
CREATE NONCLUSTERED INDEX [IX_工位人员绑定表_工位号] ON [dbo].[工位人员绑定表]
(
	[工位号] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IX_工位人员绑定表_人员编号]    Script Date: 2026/5/18 8:58:57 ******/
CREATE NONCLUSTERED INDEX [IX_工位人员绑定表_人员编号] ON [dbo].[工位人员绑定表]
(
	[人员编号] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
SET ANSI_PADDING ON
GO
/****** Object:  Index [IX_工位人员绑定表_唯一约束]    Script Date: 2026/5/18 8:58:57 ******/
CREATE UNIQUE NONCLUSTERED INDEX [IX_工位人员绑定表_唯一约束] ON [dbo].[工位人员绑定表]
(
	[工位号] ASC,
	[人员编号] ASC
)
WHERE ([绑定状态]=(1))
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IX_物料基础数据_零件图纸删除记录_删除时间]    Script Date: 2026/5/18 8:58:57 ******/
CREATE NONCLUSTERED INDEX [IX_物料基础数据_零件图纸删除记录_删除时间] ON [dbo].[物料基础数据_零件图纸删除记录]
(
	[删除时间] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
SET ANSI_PADDING ON
GO
/****** Object:  Index [IX_物料基础数据_零件图纸删除记录_物料编号]    Script Date: 2026/5/18 8:58:57 ******/
CREATE NONCLUSTERED INDEX [IX_物料基础数据_零件图纸删除记录_物料编号] ON [dbo].[物料基础数据_零件图纸删除记录]
(
	[物料编号] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
ALTER TABLE [dbo].[_日志] ADD  CONSTRAINT [DF__日志_日期]  DEFAULT (getdate()) FOR [日期]
GO
ALTER TABLE [dbo].[_日志] ADD  CONSTRAINT [DF__日志_操作日期]  DEFAULT (getdate()) FOR [操作日期]
GO
ALTER TABLE [dbo].[Attachments] ADD  DEFAULT (getdate()) FOR [UploadTime]
GO
ALTER TABLE [dbo].[Attachments] ADD  DEFAULT ((0)) FOR [IsDeleted]
GO
ALTER TABLE [dbo].[MES_接口_生产计划] ADD  CONSTRAINT [DF_MES_接口_生产计划_加急状态]  DEFAULT ((0)) FOR [加急状态]
GO
ALTER TABLE [dbo].[MES_接口_生产计划] ADD  CONSTRAINT [DF_MES_接口_生产计划_排产状态]  DEFAULT ((0)) FOR [排产状态]
GO
ALTER TABLE [dbo].[YL_加工中心_报工记录] ADD  CONSTRAINT [DF_YL_加工中心_报工记录_已确认]  DEFAULT ((0)) FOR [已确认]
GO
ALTER TABLE [dbo].[YL_加工中心_操作记录表] ADD  CONSTRAINT [DF_YL_加工中心_操作记录表_班次标准工时]  DEFAULT ((8)) FOR [班次标准工时]
GO
ALTER TABLE [dbo].[YL_质量检验_质检记录] ADD  CONSTRAINT [DF_YL_质量检验_质检记录_转至]  DEFAULT ((0)) FOR [转至]
GO
ALTER TABLE [dbo].[YL_质量检验_质检记录] ADD  CONSTRAINT [DF_YL_质量检验_质检记录_完成]  DEFAULT ((0)) FOR [完成]
GO
ALTER TABLE [dbo].[YL_质量检验_质检记录] ADD  CONSTRAINT [DF_YL_质量检验_质检记录_放行数量]  DEFAULT ((0)) FOR [放行数量]
GO
ALTER TABLE [dbo].[班次表] ADD  DEFAULT ((0)) FOR [是否删除]
GO
ALTER TABLE [dbo].[班次人员绑定表] ADD  DEFAULT ((0)) FOR [是否删除]
GO
ALTER TABLE [dbo].[车间生产管理工艺_零件工序_工艺库] ADD  CONSTRAINT [DF_车间生产管理工艺_零件工序_工艺库_启用]  DEFAULT ((0)) FOR [启用]
GO
ALTER TABLE [dbo].[车间生产管理工艺_零件生产工艺_工艺库] ADD  CONSTRAINT [DF_车间生产管理工艺_零件生产工艺_工艺库_启用]  DEFAULT ((0)) FOR [启用]
GO
ALTER TABLE [dbo].[登录基础数据_二级菜单] ADD  CONSTRAINT [DF_SCHAEFFLER_Menu_second_操作时间]  DEFAULT (getdate()) FOR [操作时间]
GO
ALTER TABLE [dbo].[登录基础数据_二级菜单] ADD  CONSTRAINT [DF_SCHAEFFLER_Menu_second_是否启用]  DEFAULT ((1)) FOR [是否启用]
GO
ALTER TABLE [dbo].[登录基础数据_人员信息] ADD  CONSTRAINT [DF_SCHAEFFLER_Personnel_Quit]  DEFAULT ((0)) FOR [Quit]
GO
ALTER TABLE [dbo].[工位人员绑定表] ADD  DEFAULT (getdate()) FOR [绑定时间]
GO
ALTER TABLE [dbo].[工位人员绑定表] ADD  DEFAULT ('系统') FOR [绑定人]
GO
ALTER TABLE [dbo].[工位人员绑定表] ADD  DEFAULT ((1)) FOR [绑定状态]
GO
ALTER TABLE [dbo].[基础数据_设备工位点检表] ADD  CONSTRAINT [DF_基础数据_设备工位点检表_操作日期]  DEFAULT (getdate()) FOR [操作日期]
GO
ALTER TABLE [dbo].[审批记录表] ADD  DEFAULT (getdate()) FOR [处理时间]
GO
ALTER TABLE [dbo].[物料基础数据_零件图纸删除记录] ADD  DEFAULT (getdate()) FOR [删除时间]
GO
ALTER TABLE [dbo].[质量检验_质检任务_SAP] ADD  CONSTRAINT [DF_质量检验_质检任务_SAP_同步时间]  DEFAULT (getdate()) FOR [同步时间]
GO
ALTER TABLE [dbo].[MES_接口_生产计划_生产任务]  WITH CHECK ADD  CONSTRAINT [FK_MES_接口_生产计划_生产任务_MES_接口_生产计划] FOREIGN KEY([订单编号])
REFERENCES [dbo].[MES_接口_生产计划] ([订单编号])
GO
ALTER TABLE [dbo].[MES_接口_生产计划_生产任务] CHECK CONSTRAINT [FK_MES_接口_生产计划_生产任务_MES_接口_生产计划]
GO
ALTER TABLE [dbo].[YL_质量检验_质检记录_检测数据]  WITH CHECK ADD  CONSTRAINT [FK_YL_质量检验_质检记录_检测数据_YL_质量检验_质检记录_检测零件] FOREIGN KEY([LJ_AID])
REFERENCES [dbo].[YL_质量检验_质检记录_检测零件] ([LJ_AID])
GO
ALTER TABLE [dbo].[YL_质量检验_质检记录_检测数据] CHECK CONSTRAINT [FK_YL_质量检验_质检记录_检测数据_YL_质量检验_质检记录_检测零件]
GO
ALTER TABLE [dbo].[车间生产管理工艺_零件工序_工艺库]  WITH CHECK ADD  CONSTRAINT [FK_车间生产管理工艺_零件工序_工艺库_基础表_工序] FOREIGN KEY([工艺编号])
REFERENCES [dbo].[基础表_工序] ([工艺编号])
GO
ALTER TABLE [dbo].[车间生产管理工艺_零件工序_工艺库] CHECK CONSTRAINT [FK_车间生产管理工艺_零件工序_工艺库_基础表_工序]
GO
ALTER TABLE [dbo].[登录基础数据_人员权限角色]  WITH CHECK ADD  CONSTRAINT [FK_SCHAEFFLER_Permissions_Roles_SCHAEFFLER_Personnel] FOREIGN KEY([Personnel_Number])
REFERENCES [dbo].[登录基础数据_人员信息] ([Personnel_Number])
GO
ALTER TABLE [dbo].[登录基础数据_人员权限角色] CHECK CONSTRAINT [FK_SCHAEFFLER_Permissions_Roles_SCHAEFFLER_Personnel]
GO
ALTER TABLE [dbo].[登录基础数据_人员权限角色]  WITH CHECK ADD  CONSTRAINT [FK_SCHAEFFLER_Permissions_Roles_SCHAEFFLER_Roles_Table] FOREIGN KEY([Roles_number])
REFERENCES [dbo].[登录基础数据_角色信息] ([Roles_number])
GO
ALTER TABLE [dbo].[登录基础数据_人员权限角色] CHECK CONSTRAINT [FK_SCHAEFFLER_Permissions_Roles_SCHAEFFLER_Roles_Table]
GO
ALTER TABLE [dbo].[登录基础数据_人员信息]  WITH CHECK ADD  CONSTRAINT [FK_SCHAEFFLER_Personnel_SCHAEFFLER_Personnel] FOREIGN KEY([Personnel_Number])
REFERENCES [dbo].[登录基础数据_人员信息] ([Personnel_Number])
GO
ALTER TABLE [dbo].[登录基础数据_人员信息] CHECK CONSTRAINT [FK_SCHAEFFLER_Personnel_SCHAEFFLER_Personnel]
GO
/****** Object:  StoredProcedure [dbo].[___DB_BAK]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE PROCEDURE [dbo].[___DB_BAK]
AS 

declare @Path nvarchar(2048) = 'C:\_MW\数据库\YL_MESDB_' + FORMAT(GETDATE(), '__yyyy_MM_dd__HH_mm_ss_fff')+'.bak'
backup database [YL_MESDB] to disk=@Path;
GO
/****** Object:  StoredProcedure [dbo].[__Reset_ProductOrder]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[__Reset_ProductOrder]
	@订单编号 int=-1,  --订单编号<0时，重置全部
	@optType int   --0重置排产,1重置加工中心
AS
BEGIN
	if(@optType=0) 
	begin
		if(@订单编号>0)
			update MES_接口_生产计划_生产任务 set 指派对象编号=null,指派对象=null,指派数量=null,计划开始时间=null,计划完成时间=null,最晚开始时间=null,
			派工状态=0,派工时间=null,派工操作人=null,任务状态=0,开工时间=null,完工时间=null,可执行=null,收料=null,收料数量=null,开工=null,首检=null,巡检=null,
			完成数量=null,进度=null,序检=null,测试=null,入库=null,加工状态=null
			where 订单编号=@订单编号
		else
			update MES_接口_生产计划_生产任务 set 指派对象编号=null,指派对象=null,指派数量=null,计划开始时间=null,计划完成时间=null,最晚开始时间=null,
			派工状态=0,派工时间=null,派工操作人=null,任务状态=0,开工时间=null,完工时间=null,可执行=null,收料=null,收料数量=null,开工=null,首检=null,巡检=null,
			完成数量=null,进度=null,序检=null,测试=null,入库=null,加工状态=null

		Update MES_接口_生产计划 set 排产状态=0
	end
	else if(@optType=1)
	begin
		if(@订单编号>0)
			update MES_接口_生产计划_生产任务 set 
			任务状态=case when 任务状态>1 then 1 else 任务状态 end,
			开工时间=null,完工时间=null,可执行=null,收料=null,收料数量=null,开工=null,首检=null,巡检=null,
			完成数量=null,进度=null,序检=null,测试=null,入库=null,加工状态=null
			where 订单编号=@订单编号
		else
			update MES_接口_生产计划_生产任务 set 
			任务状态=case when 任务状态>1 then 1 else 任务状态 end,
			开工时间=null,完工时间=null,可执行=null,收料=null,收料数量=null,开工=null,首检=null,巡检=null,
			完成数量=null,进度=null,序检=null,测试=null,入库=null,加工状态=null
	end
	truncate table YL_加工中心_操作记录表
	truncate table YL_加工中心_报工记录
END
GO
/****** Object:  StoredProcedure [dbo].[_日志_增加]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE   PROCEDURE [dbo].[_日志_增加]
@UserID  nvarchar(50)=null,
@子组件 nvarchar(50)=null,--vue 变量 ModularID
@TypeID nvarchar(50)=null,
@名称 nvarchar(200)=null,
@参数 nvarchar(max)=null

as 

SET NOCOUNT ON; 
  
if(@名称 = 'MES_机加工MES_设备数据采集_工作状态_查询') return 
declare @主模块编号 int
declare @标题	nvarchar(50)
select @主模块编号=id,@标题=title from [dbo].[登录基础数据_二级菜单] where componet=@子组件

INSERT INTO [dbo].[_日志]
           ([UserID],主模块编号, 子组件,标题
           ,[TypeID]
           ,[名称]
           ,[参数])
     VALUES
           (@UserID,@主模块编号, @子组件,@标题,@TypeID, @名称,@参数)
GO
/****** Object:  StoredProcedure [dbo].[A_Update_T_Table01]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

create PROCEDURE [dbo].[A_Update_T_Table01]
	@AID int = 0,
	@count real = 0.0
	
AS 


 UPDATE [T_Table01] SET [count] = @count 
 WHERE [AID] = @AID
GO
/****** Object:  StoredProcedure [dbo].[Event_Alarm_End]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create   PROCEDURE [dbo].[Event_Alarm_End]
@OpName nvarchar(50) = null,
@TagTypeCodeID int = 0,
@AlarmText nvarchar(2048) = null,
@AlarmLevel  nvarchar(2048) = null,
@ChangeTime datetime = null,
@TagID nvarchar(200) = null
AS

--SELECT [AID],[报警代码],[报警内容],[开始时间],[结束时间],[持续时间],[TagID],[工位号],[报警级别] FROM [报警_记录_历史_缓存]

UPDATE [报警_记录_历史_缓存] SET [结束时间] = @ChangeTime
	,[持续时间] = (SELECT DATEDIFF(Second, [开始时间], @ChangeTime) FROM [报警_记录_历史_缓存] WHERE [工位号] = @OpName AND [报警代码] = @TagTypeCodeID)
WHERE [工位号] = @OpName AND [报警代码] = @TagTypeCodeID


INSERT INTO [报警_记录_历史]([报警代码],[报警内容],[开始时间],[结束时间],[持续时间],[TagID],[工位号],[报警级别]) 
SELECT [报警代码],[报警内容],[开始时间],[结束时间],[持续时间],[TagID],[工位号],[报警级别] FROM [报警_记录_历史_缓存]
WHERE [工位号] = @OpName AND [报警代码] = @TagTypeCodeID


DELETE [报警_记录_历史_缓存]
WHERE [工位号] = @OpName AND [报警代码] = @TagTypeCodeID



--SELECT [Primarykey],[Device],[DeviceStatus],[StatusTime],[StatusCode],[MalfunctionCode],[MalfunctionName],[Malfunctionexplain],[Remark],[alarmRemove] FROM [EquipmentStatus_Backup]
--设备状态信息，关机（0）/开机（1）/报警（2）/故障（3） 运行（4） 待机（5）
INSERT INTO [EquipmentStatus_Backup]([Device],[DeviceStatus],[StatusTime],[StatusCode],[MalfunctionCode],[MalfunctionName],[Malfunctionexplain],[Remark],[alarmRemove])
VALUES(@OpName,2,@ChangeTime,2,@TagTypeCodeID,@AlarmText,'','','0')
GO
/****** Object:  StoredProcedure [dbo].[Event_Alarm_Start]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
create    PROCEDURE [dbo].[Event_Alarm_Start]
@OpName nvarchar(50) = null,
@TagTypeCodeID int = 0,
@AlarmText nvarchar(2048) = null,
@AlarmLevel  nvarchar(2048) = null,
@ChangeTime datetime = null,
@TagID nvarchar(200) = null
 AS

--SELECT [AID],[报警代码],[报警内容],[开始时间],[结束时间],[持续时间],[TagID],[工位号],[报警级别] FROM [报警_记录_历史_缓存]

INSERT INTO [报警_记录_历史_缓存] ([报警代码],[报警内容],[开始时间],[结束时间],[持续时间],[TagID],[工位号],[报警级别])
VALUES(@TagTypeCodeID,@AlarmText,@ChangeTime,null,null,@TagID,@OpName,@AlarmLevel)

--SELECT [Primarykey],[Device],[DeviceStatus],[StatusTime],[StatusCode],[MalfunctionCode],[MalfunctionName],[Malfunctionexplain],[Remark],[alarmRemove] FROM [EquipmentStatus_Backup]
--设备状态信息，关机（0）/开机（1）/报警（2）/故障（3） 运行（4） 待机（5）
INSERT INTO [EquipmentStatus_Backup]([Device],[DeviceStatus],[StatusTime],[StatusCode],[MalfunctionCode],[MalfunctionName],[Malfunctionexplain],[Remark],[alarmRemove])
VALUES(@OpName,2,@ChangeTime,2,@TagTypeCodeID,@AlarmText,'','','1')
GO
/****** Object:  StoredProcedure [dbo].[Event_CaChe_Var_Update]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE    PROCEDURE [dbo].[Event_CaChe_Var_Update]
@ChangeTime datetime = null,
@TagID nvarchar(50) = '',
@TagValue nvarchar(200) = '',
@TagValueOriginal nvarchar(200) = '',
@Zone nvarchar(50) = '',
@Sort int = -1,
@TagName nvarchar(50) = '',
@TagUnit nvarchar(50) = ''
 AS



--SELECT [AID],[CreateTime],[UpdateTime],[Zone],[Sort],[TagID],[TagName],[TagValue],[TagUnit] FROM [CaChe_Var]

if(@Zone = '加3' and @TagName = '循环时间')
begin
        declare @循环时间 int = TRY_PARSE(@TagValueOriginal AS int);
        -- 只有当转换成功时才执行（不为NULL）
        if @循环时间 IS NOT NULL
        begin
            exec [YL_设备管理_工时记录_增加] @ChangeTime, @循环时间, @Zone
        end
end

IF (SELECT COUNT([AID]) FROM [CaChe_Var] WHERE [TagID] = @TagID) > 0 BEGIN

UPDATE [CaChe_Var] SET [TagValue] = @TagValue,[UpdateTime] = @ChangeTime,TagValueOriginal=@TagValueOriginal
WHERE [TagID] = @TagID

END ELSE BEGIN

INSERT INTO [CaChe_Var] ([CreateTime],[UpdateTime],[TagID],[TagValue],[Zone],[Sort],[TagName],[TagUnit],TagValueOriginal)
VALUES(@ChangeTime,@ChangeTime,@TagID,@TagValue,@Zone,@Sort,@TagName,@TagUnit,@TagValueOriginal)

END
GO
/****** Object:  StoredProcedure [dbo].[Event_CaChe_Var_看板查询]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE    PROCEDURE [dbo].[Event_CaChe_Var_看板查询]

 AS


 SELECT [Zone]
      ,[TagName]
      ,[TagValue]
      ,[TagUnit]
  FROM [CaChe_Var]
  where [Sort] < 11
  order by Zone,Sort
GO
/****** Object:  StoredProcedure [dbo].[Event_Device_Insert_CurrInfo]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE        PROCEDURE [dbo].[Event_Device_Insert_CurrInfo]
@OpName nvarchar(2048) = null,
@TagTypeCodeID int = 0,
@TagOrderBy int = 0,
@ItemName nvarchar(2048) = null,
@TagValue nvarchar(50)  = null,
@TagValueOriginal nvarchar(200) = '',
@TagUnit nvarchar(50)  = null,
@ChangeTime datetime = null,
@TagID nvarchar(2048) = null
AS

--SELECT [AID],[工位号],[变量类型代码],[变量排序],[变量名称],[变量值],[更新时间],[TagID] FROM [历史_工位_通用]
--insert into [历史_工位_通用]([工位号],[变量类型代码],[变量排序],[变量名称],[变量值],[更新时间],[TagID])
--values(@OpName,@TagTypeCodeID,@TagOrderBy,@ItemName,@TagValue,@ChangeTime,@TagID)


-- SELECT [AID],[在线状态],[创建时间],[设备代码],[工位号],[变量类型代码],[变量名称],[值],[TagID],[DeviceCode] FROM [历史_设备数据_定时]
insert into [历史_设备数据_定时]([在线状态],[创建时间],[设备代码],[工位号],[变量类型代码],[变量名称],[值],[TagID],[DeviceCode],单位,原始值)
values(1,@ChangeTime,@OpName,@OpName,@TagTypeCodeID,@ItemName,@TagValue,@TagID,@OpName, @TagUnit,@TagValueOriginal)

GO
/****** Object:  StoredProcedure [dbo].[Event_Device_Update_CurrInfo]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


create        PROCEDURE [dbo].[Event_Device_Update_CurrInfo]
@OpName nvarchar(2048) = null,
@TagTypeCodeID int = 0,
@TagOrderBy int = 0,
@ItemName nvarchar(2048) = null,
@TagValue nvarchar(50)  = null,
@ChangeTime datetime = null,
@TagID nvarchar(2048) = null
 AS



--SELECT [AID],[工位号],[变量类型代码],[变量排序],[变量名称],[变量值],[更新时间],[TagID] FROM [当前_工位_通用]
if (select count(1) from [当前_工位_通用] where [工位号] = @OpName and [变量类型代码] = @TagTypeCodeID  and [变量排序] = @TagOrderBy ) = 0 begin

	insert into [当前_工位_通用]([工位号],[变量类型代码],[变量排序],[更新时间])
	values(@OpName,@TagTypeCodeID,@TagOrderBy,@ChangeTime)

end else begin

    update [当前_工位_通用] set 
	 [工位号] = @OpName
	,[变量类型代码] = @TagTypeCodeID
	,[变量排序] = @TagOrderBy
	,[变量名称] = @ItemName
	,[变量值] = @TagValue
	,[更新时间] = @ChangeTime
	,[TagID]  = @TagID
	 where [工位号] = @OpName and [变量类型代码] = @TagTypeCodeID and [变量排序] = @TagOrderBy
end

GO
/****** Object:  StoredProcedure [dbo].[Event_Log_Request]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

 
create PROCEDURE [dbo].[Event_Log_Request]
	@工位号 nvarchar(2048) = '',
	@日志类型 nvarchar(2048) = '',
	@TaskID nvarchar(2048) = '',
	@请求CMD nvarchar(2048) = '',
	@请求FROM nvarchar(2048) = '',
	@请求TO nvarchar(2048) = '',
    @请求时间 datetime = null,
    @请求内容 nvarchar(max) = '',
    @请求内容安全 nvarchar(max) = ''
AS 

DECLARE @CreateTime datetime = getdate()

--  SELECT [AID],[TaskID],[请求CMD],[请求FROM],[请求TO],[请求时间],[请求内容],[响应时间],[响应内容],[工位号],[日志类型] FROM [记录_日志_项目运行日志]

INSERT INTO [记录_日志_项目运行日志]([TaskID],[请求CMD],[请求FROM],[请求TO],[请求时间],[请求内容],[工位号],[日志类型],[请求内容安全])
VALUES(@TaskID,@请求CMD,@请求FROM,@请求TO,@CreateTime,@请求内容,@工位号,@日志类型,@请求内容安全)

SELECT @@IDENTITY 'AID'


GO
/****** Object:  StoredProcedure [dbo].[Event_Log_Respond]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



create PROCEDURE [dbo].[Event_Log_Respond]
    @AID bigint = null,
    @响应时间 datetime = null,
    @响应内容 nvarchar(max) = ''
AS 

DECLARE @CreateTime datetime = getdate()

----  SELECT [AID],[TaskID],[请求CMD],[请求FROM],[请求TO],[请求时间],[请求内容],[响应时间],[响应内容] FROM [记录_日志_项目运行日志]

UPDATE [记录_日志_项目运行日志] SET [响应时间] = @CreateTime,[响应内容] = @响应内容
WHERE [AID] = @AID


GO
/****** Object:  StoredProcedure [dbo].[Event_StationStatus_Insert]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

create   PROCEDURE [dbo].[Event_StationStatus_Insert]
@OpName nvarchar(2048) = null,
@DeviceCode nvarchar(2048) = null,
@Status int = null,
@AutoMode int = null,
@ChangeTime datetime = null
AS


--210：设备状态：-1关机，0待机，1工作；2报警；3暂停
--SELECT [AID],[工位号],[订单号],[产品型号],[工号],[零件号],[设备状态],[电流1],[电流2],[电流3],[线电压1],[线电压2],[线电压3],[功率1],[功率2],[功率3],[总功率],[电能],[创建时间],[自动模式] FROM [历史_工位设备状态每分钟记录]
INSERT INTO [历史_工位设备状态每分钟记录] ([工位号],[设备状态],[创建时间],[自动模式],[DeviceCode])
VALUES(@OpName,@Status,@ChangeTime,@AutoMode,@DeviceCode)

GO
/****** Object:  StoredProcedure [dbo].[Event_StationStatus_Update]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

create   PROCEDURE [dbo].[Event_StationStatus_Update]
@OpName nvarchar(2048) = null,
@DeviceCode nvarchar(2048) = null,
@Status int = null,
@AutoMode int = null,
@ChangeTime datetime = null
AS

--214：设备状态：-1关机，0待机，1工作；2报警；3暂停
--判断设备状态发生变化
--DECLARE @状态代码 int = 0;
--SELECT TOP 1 @状态代码 = ISNULL([状态代码],-1) FROM  [基础_工位] WHERE [工位号] = @OpName

--DECLARE @设备编号 nvarchar(2048) = '';
--SELECT TOP 1 @设备编号 = ISNULL([设备编号],'') FROM  [基础_设备] WHERE [工位号] = @OpName

--IF @状态代码 != @Status BEGIN

--UPDATE [基础_工位] SET [状态代码变化前] = @状态代码,[状态更新时间变化前] = @ChangeTime WHERE [工位号] = @OpName
--EXEC [设备管理_状态变化新增] @opName ,@设备编号 ,@Status ,@ChangeTime 

--END

--修改状态代码
UPDATE [基础_工位] SET [状态代码] = @Status,[自动模式] = @AutoMode,[状态更新时间] = @ChangeTime WHERE [工位号] = @OpName


GO
/****** Object:  StoredProcedure [dbo].[FindUnfinishedStartOperations]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[FindUnfinishedStartOperations]
AS
BEGIN
    SET NOCOUNT ON;

    SELECT 
        AID,
        操作类别编号,
        操作类别,
        阶段标识,
        工序名称,
        工位名称,
        操作人 as 指派对象,
        合同号,
        订单编号 as 订单号,
        物料编号 as 产品编码,
        物料描述 as 产品名称,
        操作数值,
        操作内容,
        TaskAID,
        开始时间,
        结束时间,
        实际工时 as 加工工时,
        暂停时长,
        总时长
    FROM YL_加工中心_操作记录表
    WHERE 操作内容 = '开始加工' 
      AND 结束时间 IS NULL
      AND NOT EXISTS (
          SELECT 1 
          FROM YL_加工中心_操作记录表 t2 
          WHERE t2.操作内容 = '报工' 
            AND t2.TaskAID = YL_加工中心_操作记录表.TaskAID
            AND t2.开始时间 = YL_加工中心_操作记录表.开始时间
      )
    ORDER BY 开始时间 DESC;
END
GO
/****** Object:  StoredProcedure [dbo].[MES_DeviceAdmin_BaseInfo]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[MES_DeviceAdmin_BaseInfo]
    @设备编号 NVARCHAR(50),
    @设备名称 NVARCHAR(100),
    @型号规格 NVARCHAR(100) = NULL,
    @制造商 NVARCHAR(100) = NULL,
    @所属车间 NVARCHAR(50) = NULL,
    @安装日期 DATE = NULL,
    @预期寿命 INT = NULL,
    @状态 INT = 0, -- -- 0:正常（默认） 1:维修 2:报废
    @最后维护日期 DATETIME = NULL,
    @责任人 NVARCHAR(50) = NULL,
    @技术参数JSON NVARCHAR(MAX) = NULL
AS
BEGIN
    SET NOCOUNT ON;
    
    BEGIN TRY
        -- 检查设备编号是否已存在
        IF EXISTS (SELECT 1 FROM [dbo].[YL_设备管理_设备台账] WHERE [设备编号] = @设备编号)
        BEGIN
            RAISERROR('设备编号已存在，请勿重复添加', 16, 1);
            RETURN -1;
        END
        
        -- 插入新记录
        INSERT INTO [dbo].[YL_设备管理_设备台账] (
            [设备编号],
            [设备名称],
            [型号规格],
            [制造商],
            [所属车间],
            [安装日期],
            [预期寿命],
            [状态],
            [最后维护日期],
            [责任人],
            [技术参数JSON]
        )
        VALUES (
            @设备编号,
            @设备名称,
            @型号规格,
            @制造商,
            @所属车间,
            @安装日期,
            @预期寿命,
            @状态,
            @最后维护日期,
            @责任人,
            @技术参数JSON
        );
        
        RETURN SCOPE_IDENTITY(); -- 返回新插入的设备ID
    END TRY
    BEGIN CATCH
        DECLARE @ErrorMessage NVARCHAR(4000) = ERROR_MESSAGE();
        RAISERROR(@ErrorMessage, 16, 1);
        RETURN -1;
    END CATCH
END
GO
/****** Object:  StoredProcedure [dbo].[MES_DeviceAdmin_DeviceProductState_Update]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[MES_DeviceAdmin_DeviceProductState_Update]
    @设备编号 NVARCHAR(50),
    @设备名称 NVARCHAR(50) = NULL,
    @阶段标识 INT = NULL,
    @工序名称 NVARCHAR(50) = NULL,
    @工位编号 NVARCHAR(50),
    @工位名称 NVARCHAR(50) = NULL,
    @设备状态 INT,
    @操作人 NVARCHAR(50),
    @TaskAID INT = NULL
AS
BEGIN
    SET NOCOUNT ON;
    
    DECLARE @当前时间 DATETIME = GETDATE();
    
    -- 检查设备编号是否存在
    IF EXISTS (SELECT 1 FROM [dbo].[YL_设备管理_设备生产状态_Moby] WHERE [设备编号] = @设备编号)
    BEGIN
        -- 更新现有记录
        UPDATE [dbo].[YL_设备管理_设备生产状态_Moby]
        SET 
            --[设备名称] = ISNULL(@设备名称, [设备名称]),
            --[阶段标识] = ISNULL(@阶段标识, [阶段标识]),
            --[工序名称] = ISNULL(@工序名称, [工序名称]),
            --[工位编号] = @工位编号,
            --[工位名称] = ISNULL(@工位名称, [工位名称]),
            [设备状态] = @设备状态,
            [操作人] = @操作人,
            [TaskAID] = ISNULL(@TaskAID, [TaskAID]),
            [操作时间] = @当前时间
        WHERE [设备编号] = @设备编号;
    END
    ELSE
    BEGIN
        -- 插入新记录
        INSERT INTO [dbo].[YL_设备管理_设备生产状态_Moby] (
            [设备编号],
            [设备名称],
            [阶段标识],
            [工序名称],
            [工位编号],
            [工位名称],
            [设备状态],
            [操作人],
            [TaskAID],
            [操作时间]
        )
        VALUES (
            @设备编号,
            @设备名称,
            @阶段标识,
            @工序名称,
            @工位编号,
            @工位名称,
            @设备状态,
            @操作人,
            @TaskAID,
            @当前时间
        );
    END
    
    -- 无论新增还是更新，都将记录插入历史表
    INSERT INTO [dbo].[YL_设备管理_设备生产状态_Moby_历史记录] (
        [设备编号],
        [设备名称],
        [阶段标识],
        [工序名称],
        [工位编号],
        [工位名称],
        [设备状态],
        [操作人],
        [TaskAID],
        [操作时间]
    )
    SELECT 
        [设备编号],
        [设备名称],
        [阶段标识],
        [工序名称],
        [工位编号],
        [工位名称],
        [设备状态],
        [操作人],
        [TaskAID],
        [操作时间]
    FROM [dbo].[YL_设备管理_设备生产状态_Moby]
    WHERE [设备编号] = @设备编号;
    
    RETURN 0;
END
GO
/****** Object:  StoredProcedure [dbo].[MES_DeviceAdmin_ProductState_HistoryQuery]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[MES_DeviceAdmin_ProductState_HistoryQuery]
    @设备名称 NVARCHAR(50) = NULL,
    @工序名称 NVARCHAR(50) = NULL,
    @工位名称 NVARCHAR(50) = NULL,
    @设备状态 INT = NULL,
    @操作人 NVARCHAR(50) = NULL,
    @操作时间开始 DATETIME = NULL,
    @操作时间结束 DATETIME = NULL,
    @设备编号 NVARCHAR(50) = NULL
AS
BEGIN
    SET NOCOUNT ON;
    
    SELECT 
        [AID],
        [设备编号],
        [设备名称],
        [阶段标识],
        [工序名称],
        [工位编号],
        [工位名称],
        [设备状态],
        [操作人],
        [TaskAID],
        [操作时间]
    FROM 
        [dbo].[YL_设备管理_设备生产状态_Moby_历史记录]
    WHERE 
        ([设备编号] = @设备编号 OR @设备编号 IS NULL)
        AND ([设备名称] LIKE '%' + ISNULL(@设备名称, '') + '%' OR @设备名称 IS NULL)
        AND ([工序名称] LIKE '%' + ISNULL(@工序名称, '') + '%' OR @工序名称 IS NULL)
        AND ([工位名称] LIKE '%' + ISNULL(@工位名称, '') + '%' OR @工位名称 IS NULL)
        AND ([设备状态] = @设备状态 OR @设备状态 IS NULL)
        AND ([操作人] LIKE '%' + ISNULL(@操作人, '') + '%' OR @操作人 IS NULL)
        AND ([操作时间] >= @操作时间开始 OR @操作时间开始 IS NULL)
        AND ([操作时间] <= @操作时间结束 OR @操作时间结束 IS NULL)
    ORDER BY 
        [操作时间] DESC;
END
GO
/****** Object:  StoredProcedure [dbo].[MES_DeviceAdmin_ProductState_MobyQuery]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[MES_DeviceAdmin_ProductState_MobyQuery]
    @设备名称 NVARCHAR(50) = NULL,
    @工序名称 NVARCHAR(50) = NULL,
    @工位名称 NVARCHAR(50) = NULL,
    @设备状态 INT = NULL,
    @操作人 NVARCHAR(50) = NULL,
    @操作时间开始 DATETIME = NULL,
    @操作时间结束 DATETIME = NULL
AS
BEGIN
    SET NOCOUNT ON;
    
    SELECT 
        [AID],
        [设备编号],
        [设备名称],
        [阶段标识],
        [工序名称],
        [工位编号],
        [工位名称],
        [设备状态],
        [操作人],
        [TaskAID],
        [操作时间]
    FROM 
        [dbo].[YL_设备管理_设备生产状态_Moby]
    WHERE 
        ([设备名称] LIKE '%' + ISNULL(@设备名称, '') + '%' OR @设备名称 IS NULL)
        AND ([工序名称] LIKE '%' + ISNULL(@工序名称, '') + '%' OR @工序名称 IS NULL)
        AND ([工位名称] LIKE '%' + ISNULL(@工位名称, '') + '%' OR @工位名称 IS NULL)
        AND ([设备状态] = @设备状态 OR @设备状态 IS NULL)
        AND ([操作人] LIKE '%' + ISNULL(@操作人, '') + '%' OR @操作人 IS NULL)
        AND ([操作时间] >= @操作时间开始 OR @操作时间开始 IS NULL)
        AND ([操作时间] <= @操作时间结束 OR @操作时间结束 IS NULL)
    ORDER BY 
        [操作时间] DESC;
END
GO
/****** Object:  StoredProcedure [dbo].[MES_DeviceAdmin_RepairRecords_Add]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- 创建存储过程：YL_设备管理_维修记录_新增
CREATE PROCEDURE [dbo].[MES_DeviceAdmin_RepairRecords_Add]
    @工位编号 NVARCHAR(50),
    @工位名称 NVARCHAR(50),
    @设备编号 NVARCHAR(50),
    @设备名称 NVARCHAR(50),
    @设备规格型号 NVARCHAR(50),
    @故障描述 NVARCHAR(2000),
    @故障时间 DATETIME,
    @维修人员 NVARCHAR(50),
    @维修完成时间 DATETIME
AS
BEGIN
    SET NOCOUNT ON;
    
    BEGIN TRY
        -- 插入新记录
        INSERT INTO [dbo].[YL_设备管理_维修记录] (
            [工位编号],
            [工位名称],
            [设备编号],
            [设备名称],
            [设备规格型号],
            [故障描述],
            [故障时间],
            [维修人员],
            [维修完成时间]
        ) VALUES (
            @工位编号,
            @工位名称,
            @设备编号,
            @设备名称,
            @设备规格型号,
            @故障描述,
            @故障时间,
            @维修人员,
            @维修完成时间
        );
        
        -- 返回新插入记录的AID
        SELECT SCOPE_IDENTITY() AS '新记录AID';
        
        RETURN 0; -- 成功
    END TRY
    BEGIN CATCH
        -- 返回错误信息
        SELECT 
            ERROR_NUMBER() AS ErrorNumber,
            ERROR_MESSAGE() AS ErrorMessage;
            
        RETURN -1; -- 失败
    END CATCH
END
GO
/****** Object:  StoredProcedure [dbo].[MES_DeviceAdmin_RepairRecords_Query]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[MES_DeviceAdmin_RepairRecords_Query]
    @工位编号 NVARCHAR(50) = NULL,
    @设备名称 NVARCHAR(100) = NULL,
    @故障描述 NVARCHAR(500) = NULL,
    @故障时间开始 DATETIME = NULL,
    @故障时间结束 DATETIME = NULL,
    @维修人员 NVARCHAR(50) = NULL
AS
BEGIN
    SET NOCOUNT ON;
    
    SELECT [AID]
          ,[工位编号]
          ,[工位名称]
          ,[设备编号]
          ,[设备名称]
          ,[设备规格型号]
          ,[故障描述]
          ,[故障时间]
          ,[维修人员]
          ,[维修完成时间]
    FROM [YL_设备管理_维修记录]
    WHERE 
        ([工位编号] = @工位编号 OR @工位编号 IS NULL)
        AND ([设备名称] LIKE '%' + @设备名称 + '%' OR @设备名称 IS NULL)
        AND ([故障描述] LIKE '%' + @故障描述 + '%' OR @故障描述 IS NULL)
        AND ([故障时间] >= @故障时间开始 OR @故障时间开始 IS NULL)
        AND ([故障时间] <= @故障时间结束 OR @故障时间结束 IS NULL)
        AND ([维修人员] = @维修人员 OR @维修人员 IS NULL)
    ORDER BY [故障时间] DESC;
END
GO
/****** Object:  StoredProcedure [dbo].[MES_GetDicItemID_ByDicItemName]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[MES_GetDicItemID_ByDicItemName]
	@dicItemName nvarchar(50),
	@dicDataType nvarchar(50)
AS
BEGIN
	SELECT [词条编号] FROM [YL_基础表_数据字典] WHERE [词条名称]=@dicItemName AND [数据类别]=@dicDataType
END

GO
/****** Object:  StoredProcedure [dbo].[MES_OrderPlanned_ChildTask_Add]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[MES_OrderPlanned_ChildTask_Add]
    @TaskAID BIGINT,
    @任务描述 NVARCHAR(500) = NULL,
    @指派对象 NVARCHAR(50) = NULL,
	@指派对象编号 NVARCHAR(50) = NULL,
    @指派数量 INT = NULL,
    @计划开始时间 DATETIME = NULL,
    @计划结束时间 DATETIME = NULL,
	@最晚开始时间 DATETIME = NULL
AS
BEGIN
    SET NOCOUNT ON;
    
    BEGIN TRY
        BEGIN TRANSACTION;
        
        INSERT INTO [dbo].[MES_接口_生产计划_生产任务_子任务]
        (
            [TaskAID],
            [任务描述],
            [指派对象],
			[指派对象编号],
            [指派数量],
            [计划开始时间],
            [计划结束时间],
			[最晚开始时间]
        )
        VALUES
        (
            @TaskAID,
            @任务描述,
            @指派对象,
			@指派对象编号,
            @指派数量,
            @计划开始时间,
            @计划结束时间,
			@最晚开始时间
        );
        
        -- 返回新插入记录的AID
        SELECT SCOPE_IDENTITY() AS NewAID;
        
        COMMIT TRANSACTION;
    END TRY
    BEGIN CATCH
        IF @@TRANCOUNT > 0
            ROLLBACK TRANSACTION;
            
        -- 返回错误信息
        DECLARE @ErrorMessage NVARCHAR(4000) = ERROR_MESSAGE();
        DECLARE @ErrorSeverity INT = ERROR_SEVERITY();
        DECLARE @ErrorState INT = ERROR_STATE();
        
        RAISERROR(@ErrorMessage, @ErrorSeverity, @ErrorState);
    END CATCH
END
GO
/****** Object:  StoredProcedure [dbo].[MES_OrderPlanned_ChildTask_Get]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[MES_OrderPlanned_ChildTask_Get]
    @TaskAID BIGINT

AS

SELECT 
[AID],
[TaskAID],
[任务描述],
[指派对象],
[指派对象编号],
[指派数量],
[计划开始时间],
[计划结束时间] as 计划完成时间,
[最晚开始时间] 
from [MES_接口_生产计划_生产任务_子任务] 
        

            
GO
/****** Object:  StoredProcedure [dbo].[MES_OrderPlanned_DescriptionEdit]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[MES_OrderPlanned_DescriptionEdit]
@订单号 int,
@订单行号 int,
@订单拆分内码 int,
@优先级 nvarchar(50)='',
@未完成说明 nvarchar(50)='',
@派工特殊说明 nvarchar(500)='',
@最后编辑人 nvarchar(500)=''

AS

Update [MES_接口_生产计划_生产任务] set 
	优先级=@优先级,
	未完成说明=@未完成说明,
	派工特殊说明=@派工特殊说明,
	最后编辑人=@最后编辑人,
	最后编辑时间=getdate()
WHERE 订单编号=@订单号 and 订单行号=@订单行号 and 订单拆分内码=@订单拆分内码
GO
/****** Object:  StoredProcedure [dbo].[MES_OrderPlanned_EditTaskPlanned]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[MES_OrderPlanned_EditTaskPlanned]
	@editstr nvarchar(50),
	@订单号 int=0,
	@订单行号 int =0,
	@订单拆分内码 int =0
AS
declare @whereStr nvarchar(max)=' where 1=1 '
declare @updateStr nvarchar(max)='update [MES_接口_生产计划_生产任务] set '
declare @selStr nvarchar(max)=''

--		update [MES_接口_生产计划_生产任务] set [计划数量] = @未指派数量_剩余 where 订单编号=@订单号 and 订单行号=@订单行号 and 订单拆分内码<>@订单拆分内码 and isnull(派工状态,0)=0
	if(@订单号>0)set @whereStr=@whereStr + ' and [订单编号]='+Convert(VARCHAR(10),@订单号)
	if(@订单行号>0)set @whereStr=@whereStr + ' and [订单行号]='+Convert(VARCHAR(10),@订单行号)
	if(@订单拆分内码>0)set @whereStr=@whereStr + ' and [订单拆分内码]='+Convert(VARCHAR(10),@订单拆分内码)
	if(@editstr<>'')set @updateStr = @updateStr + @editstr
	set @selStr=@updateStr+@whereStr

print @selStr
EXEC sp_executesql @selStr


GO
/****** Object:  StoredProcedure [dbo].[MES_OrderPlanned_Finish]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[MES_OrderPlanned_Finish]
    @任务列表 NVARCHAR(MAX),  -- JSON 格式：'[{"任务ID":"1001","指派对象":"张三"},...]'
	@派工操作人 NVARCHAR(MAX)
AS
BEGIN
    UPDATE t
    SET 
        t.[排产状态] = 1,
        t.[任务状态] = 0,
        t.[指派对象] = j.指派对象,
		t.指派数量 = j.指派数量,
		t.指派对象编号 = j.指派对象编号,
		t.派工特殊说明 = j.派工特殊说明,
		t.计划开始时间 = j.计划开始时间,
		t.计划完成时间 = j.计划完成时间,
		t.最晚开始时间 = j.最晚开始时间,
		t.派工操作人 = @派工操作人,
		t.最后编辑人 = @派工操作人,
		t.最后编辑时间 = GETDATE(),
        t.[修改时间] = GETDATE()
    FROM [MES_接口_生产计划_生产任务] t
    INNER JOIN (
        SELECT 
			TaskAID = JSON_VALUE(value, '$.taskaid'),
			指派对象 = JSON_VALUE(value, '$."指派对象"'),
			指派数量 = JSON_VALUE(value, '$."指派数量"'),
			指派对象编号 = JSON_VALUE(value, '$."指派对象编号"'),
			派工特殊说明 = JSON_VALUE(value, '$."派工特殊说明"'),
			计划开始时间 = JSON_VALUE(value, '$."计划开始时间"'),
			计划完成时间 = JSON_VALUE(value, '$."计划完成时间"'),
			最晚开始时间 = JSON_VALUE(value, '$."最晚开始时间"')
        FROM OPENJSON(@任务列表)
    ) j ON t.[AID] = j.TaskAID;

END
GO
/****** Object:  StoredProcedure [dbo].[MES_OrderPlanned_Query]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[MES_OrderPlanned_Query]
@订单号 int=0,
@物料类型 nvarchar(50)='',   --自制件、装配件
@合同号 nvarchar(50)='',
@产品编码  nvarchar(50)='',
@产品名称  nvarchar(50)='',
@工序名称  nvarchar(50)='',
@要求完工日期1  nvarchar(50)='',
@要求完工日期2  nvarchar(50)='',
@计划开始1 nvarchar(50)='',
@计划开始2 nvarchar(50)='',
@计划完成1 nvarchar(50)='',
@计划完成2 nvarchar(50)='',
@排产状态  nvarchar(50)='全部' ,  --全部，已完成、未完成
@指派对象  nvarchar(50)='全部'
AS
BEGIN
    declare @selectStr nvarchar(4000)
    declare @selectStrWhere nvarchar(4000)=' where [物料类型]=''pit_Resource'' and [自制件属性]= ''机加件'' and isnull(v.任务状态,0) < 4'
    
    if(@物料类型='自制件')   --自制件
        set @selectStr='
            SELECT  [计划数量订单],isnull(开工时间,0) as 开工时间,isnull(进度,0) as 进度,[TaskAID],[合同号],v.[订单编号] as 订单号,
            [订单行号],[订单拆分内码] as 拆分内码,[物料编号] as 产品编码,[物料描述] as 产品名称,TRIM(''.'' FROM TRIM(''0'' FROM CAST(v.[计划数量] AS VARCHAR(30)))) AS 计划数量,
            [计划完成] as 要求完工日期,[工序名称],完成数量,v.计划号,收料数量,外协分组,v.任务状态,v.备注,
            case when [加急状态]=1 then ''加急'' else '''' end as 加急状态,性质,isnull(总工时,0) as 总工时,[占用情况]
            ,[排产状态],[工序计划数量],指派对象编号,指派对象,TRIM(''.'' FROM TRIM(''0'' FROM CAST([指派数量] AS VARCHAR(30)))) AS 指派数量,计划开始时间,计划完成时间,最晚开始时间,
            [派工状态],[外协通知],[优先级],[未完成说明],[派工特殊说明],[最后编辑人],[最后编辑时间],[二次派工],isnull(g.标准工时,0) as 标准工时,
            case when zj.计划号 is not null then ''是'' else ''否'' end as 终检 
            FROM [View_生产订单_MES] v
            LEFT JOIN (
                SELECT DISTINCT 计划号
                FROM dbo.YL_质量检验_质检记录
                WHERE 质检类型 = ''终检''
            ) zj ON v.[订单编号] = zj.计划号
			 LEFT JOIN [dbo].[车间生产管理工艺_零件生产工艺_工艺库] g  -- 新增LEFT JOIN
                ON v.[订单编号] = g.订单编号 
                AND v.[订单行号] = g.工艺顺序'
    --else   --装配件
    --    set @selectStr='
    --        SELECT [计划数量订单],isnull(开工时间,0) as 开工时间,isnull(进度,0) as 进度,[TaskAID],[合同号],[订单编号] as 订单号,
    --        [订单行号],[订单拆分内码] as 拆分内码,[物料编号] as 产品编码,[物料描述] as 产品名称,[计划数量],
    --        '''' as 合同交货期,[计划完成] as 预计齐套时间,''齐'' as 是否齐套,'''' as 齐套检测,''是'' as 齐套锁料,
    --        [计划开始] as 备料日期,0 as 加急状态,isnull(总工时,0) as 总工时,[工序名称],
    --        case when [加急状态]=1 then ''加急'' else '''' end as 加急状态,性质,总工时,[占用情况]
    --        ,[排产状态],[工序计划数量],指派对象编号,指派对象,指派数量,计划开始时间,计划完成时间,最晚开始时间,
    --        [派工状态],[外协通知],[优先级],[未完成说明],[派工特殊说明],[最后编辑人],[最后编辑时间],[二次派工],
    --        case when zj.计划号 is not null then ''是'' else ''否'' end as 终检
    --        FROM [View_生产订单_MES] v
    --        LEFT JOIN (
    --            SELECT DISTINCT 计划号
    --            FROM dbo.YL_质量检验_质检记录
    --            WHERE 质检类型 = ''终检''
    --        ) zj ON v.[订单编号] = zj.计划号'

    if(@订单号>0)set @selectStrWhere=@selectStrWhere + ' and v.[订单编号]='+Convert(VARCHAR(10),@订单号)
    if(@合同号<>'')set @selectStrWhere=@selectStrWhere + ' and [合同号] like ''%'+@合同号+'%'''
    if(@产品编码<>'')set @selectStrWhere=@selectStrWhere + ' and [物料编号] like ''%'+@产品编码+'%'''
    if(@产品名称<>'')set @selectStrWhere=@selectStrWhere + ' and [物料描述] like ''%'+@产品名称+'%'''
    if(@工序名称<>'')set @selectStrWhere=@selectStrWhere + ' and [工序名称] = '''+@工序名称+''''
    if(@要求完工日期1 <>'')set @selectStrWhere=@selectStrWhere + ' and [计划完成] >= '''+@要求完工日期1+''''
    if(@要求完工日期2 <>'')set @selectStrWhere=@selectStrWhere + ' and [计划完成] <= '''+@要求完工日期2+''''
    if(@计划开始1 <>'')set @selectStrWhere=@selectStrWhere + ' and [计划开始时间] >= '''+@计划开始1+''''
    if(@计划开始2 <>'')set @selectStrWhere=@selectStrWhere + ' and [计划开始时间] <= '''+@计划开始2+''''
    if(@计划完成1 <>'')set @selectStrWhere=@selectStrWhere + ' and [计划完成时间] >= '''+@计划完成1+''''
    if(@计划完成2 <>'')set @selectStrWhere=@selectStrWhere + ' and [计划完成时间] <= '''+@计划完成2+''''
    if(@排产状态='未完成')set @selectStrWhere=@selectStrWhere + ' and isnull([排产状态],0) = 0'
    else if(@排产状态='已完成')set @selectStrWhere=@selectStrWhere + ' and [排产状态] = 1'
    if(@物料类型='自制件') set @selectStrWhere=@selectStrWhere + ' and [不装配] <> ''否'''
    if(@物料类型='装配件') set @selectStrWhere=@selectStrWhere + ' and [不装配] = ''否'''
    if(@指派对象<>'全部') set @selectStrWhere=@selectStrWhere + ' and [指派对象] in (SELECT value FROM STRING_SPLIT('''+@指派对象+''', '',''))'
    
    set @selectStr=@selectStr+@selectStrWhere
    print @selectStr
    EXEC sp_executesql @selectStr
END
GO
/****** Object:  StoredProcedure [dbo].[MES_OrderPlanned_Queryzp]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[MES_OrderPlanned_Queryzp]
@订单号 int=0,
@物料类型 nvarchar(50)='',   --自制件、装配件
@合同号 nvarchar(50)='',
@产品编码  nvarchar(50)='',
@产品名称  nvarchar(50)='',
@工序名称  nvarchar(50)='',
@要求完工日期1  nvarchar(50)='',
@要求完工日期2  nvarchar(50)='',
@计划开始1 nvarchar(50)='',
@计划开始2 nvarchar(50)='',
@计划完成1 nvarchar(50)='',
@计划完成2 nvarchar(50)='',
@排产状态  nvarchar(50)='全部' ,  --全部，已完成、未完成
@指派对象  nvarchar(50)='全部'
AS
BEGIN
    declare @selectStr nvarchar(4000)
    declare @selectStrWhere nvarchar(4000)=' where [物料类型]=''pit_Resource'' and [自制件属性] like ''%装配%'''
    
    if(@物料类型='自制件')   --自制件
        --set @selectStr='
        --    SELECT [计划数量订单],isnull(开工时间,0) as 开工时间,isnull(进度,0) as 进度,[TaskAID],[合同号],[订单编号] as 订单号,
        --    [订单行号],[订单拆分内码] as 拆分内码,[物料编号] as 产品编码,[物料描述] as 产品名称,TRIM(''.'' FROM TRIM(''0'' FROM CAST([计划数量] AS VARCHAR(30)))) AS 计划数量,
        --    [计划完成] as 要求完工日期,[工序名称],完成数量,v.计划号,
        --    case when [加急状态]=1 then ''加急'' else '''' end as 加急状态,性质,isnull(总工时,0) as 总工时,[占用情况]
        --    ,[排产状态],[工序计划数量],指派对象编号,指派对象,TRIM(''.'' FROM TRIM(''0'' FROM CAST([指派数量] AS VARCHAR(30)))) AS 指派数量,计划开始时间,计划完成时间,最晚开始时间,
        --    [派工状态],[外协通知],[优先级],[未完成说明],[派工特殊说明],[最后编辑人],[最后编辑时间],[二次派工],
        --    case when zj.计划号 is not null then ''是'' else ''否'' end as 终检
        --    FROM [View_生产订单_MES] v
        --    LEFT JOIN (
        --        SELECT DISTINCT 计划号
        --        FROM dbo.YL_质量检验_质检记录
        --        WHERE 质检类型 = ''终检''
        --    ) zj ON v.[订单编号] = zj.计划号'
		set @selectStr='
            SELECT top 100 [计划数量订单],isnull(开工时间,0) as 开工时间,isnull(进度,0) as 进度,[TaskAID],[合同号],v.[订单编号] as 订单号,
            [订单行号],[订单拆分内码] as 拆分内码,[物料编号] as 产品编码,[物料描述] as 产品名称,TRIM(''.'' FROM TRIM(''0'' FROM CAST(v.[计划数量] AS VARCHAR(30)))) AS 计划数量,
            [计划完成] as 要求完工日期,[工序名称],完成数量,v.计划号,收料数量,外协分组,v.任务状态,
            case when [加急状态]=1 then ''加急'' else '''' end as 加急状态,性质,isnull(总工时,0) as 总工时,[占用情况]
            ,[排产状态],[工序计划数量],指派对象编号,指派对象,TRIM(''.'' FROM TRIM(''0'' FROM CAST([指派数量] AS VARCHAR(30)))) AS 指派数量,计划开始时间,计划完成时间,最晚开始时间,
            [派工状态],[外协通知],[优先级],[未完成说明],[派工特殊说明],[最后编辑人],[最后编辑时间],[二次派工],
            case when zj.计划号 is not null then ''是'' else ''否'' end as 终检,ISNULL(g.标准工时, 0) as 标准工时 
            FROM [View_生产订单_MES] v
            LEFT JOIN (
                SELECT DISTINCT 计划号
                FROM dbo.YL_质量检验_质检记录
                WHERE 质检类型 = ''终检''
            ) zj ON v.[订单编号] = zj.计划号
			 LEFT JOIN [dbo].[车间生产管理工艺_零件生产工艺_工艺库] g  -- 新增LEFT JOIN
                ON v.[订单编号] = g.订单编号 
                AND v.[订单行号] = g.工艺顺序'
    --else   --装配件
    --    set @selectStr='
    --        SELECT [计划数量订单],isnull(开工时间,0) as 开工时间,isnull(进度,0) as 进度,[TaskAID],[合同号],[订单编号] as 订单号,
    --        [订单行号],[订单拆分内码] as 拆分内码,[物料编号] as 产品编码,[物料描述] as 产品名称,[计划数量],
    --        '''' as 合同交货期,[计划完成] as 预计齐套时间,''齐'' as 是否齐套,'''' as 齐套检测,''是'' as 齐套锁料,
    --        [计划开始] as 备料日期,0 as 加急状态,isnull(总工时,0) as 总工时,[工序名称],
    --        case when [加急状态]=1 then ''加急'' else '''' end as 加急状态,性质,总工时,[占用情况]
    --        ,[排产状态],[工序计划数量],指派对象编号,指派对象,指派数量,计划开始时间,计划完成时间,最晚开始时间,
    --        [派工状态],[外协通知],[优先级],[未完成说明],[派工特殊说明],[最后编辑人],[最后编辑时间],[二次派工],
    --        case when zj.计划号 is not null then ''是'' else ''否'' end as 终检
    --        FROM [View_生产订单_MES] v
    --        LEFT JOIN (
    --            SELECT DISTINCT 计划号
    --            FROM dbo.YL_质量检验_质检记录
    --            WHERE 质检类型 = ''终检''
    --        ) zj ON v.[订单编号] = zj.计划号'

    if(@订单号>0)set @selectStrWhere=@selectStrWhere + ' and v.[订单编号]='+Convert(VARCHAR(10),@订单号)
    if(@合同号<>'')set @selectStrWhere=@selectStrWhere + ' and [合同号] like ''%'+@合同号+'%'''
    if(@产品编码<>'')set @selectStrWhere=@selectStrWhere + ' and [物料编号] like ''%'+@产品编码+'%'''
    if(@产品名称<>'')set @selectStrWhere=@selectStrWhere + ' and [物料描述] like ''%'+@产品名称+'%'''
    if(@工序名称<>'')set @selectStrWhere=@selectStrWhere + ' and [工序名称] = '''+@工序名称+''''
    if(@要求完工日期1 <>'')set @selectStrWhere=@selectStrWhere + ' and [计划完成] >= '''+@要求完工日期1+''''
    if(@要求完工日期2 <>'')set @selectStrWhere=@selectStrWhere + ' and [计划完成] <= '''+@要求完工日期2+''''
    if(@计划开始1 <>'')set @selectStrWhere=@selectStrWhere + ' and [计划开始时间] >= '''+@计划开始1+''''
    if(@计划开始2 <>'')set @selectStrWhere=@selectStrWhere + ' and [计划开始时间] <= '''+@计划开始2+''''
    if(@计划完成1 <>'')set @selectStrWhere=@selectStrWhere + ' and [计划完成时间] >= '''+@计划完成1+''''
    if(@计划完成2 <>'')set @selectStrWhere=@selectStrWhere + ' and [计划完成时间] <= '''+@计划完成2+''''
    if(@排产状态='未完成')set @selectStrWhere=@selectStrWhere + ' and isnull([排产状态],0) = 0'
    else if(@排产状态='已完成')set @selectStrWhere=@selectStrWhere + ' and [排产状态] = 1'
    if(@物料类型='自制件') set @selectStrWhere=@selectStrWhere + ' and [不装配] <> ''否'''
    if(@物料类型='装配件') set @selectStrWhere=@selectStrWhere + ' and [不装配] = ''否'''
    if(@指派对象<>'全部') set @selectStrWhere=@selectStrWhere + ' and [指派对象] in (SELECT value FROM STRING_SPLIT('''+@指派对象+''', '',''))'
    
    set @selectStr=@selectStr+@selectStrWhere
    print @selectStr
    EXEC sp_executesql @selectStr
END
GO
/****** Object:  StoredProcedure [dbo].[MES_OrderPlanned_SingleTaskPlanned]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		赵艳华
-- Create date: 2025-03-30
-- Description:	计划排产、拆分
-- =============================================
CREATE PROCEDURE [dbo].[MES_OrderPlanned_SingleTaskPlanned] 
@订单号 int=0,
@订单行号 int =0,
@订单拆分内码 int =0,
@指派对象编号 nvarchar(50) ='',
@指派对象 nvarchar(50) ='',
@指派数量 int =0,
@派工特殊说明 nvarchar(500) ='',
@计划开始时间 nvarchar(50) ='',
@计划完成时间 nvarchar(50) ='',
@最晚开始时间 nvarchar(50) ='',
@派工操作人 nvarchar(50) =''

AS

declare @ErrMsg nvarchar(500) ='' 
declare @计划数量 decimal(16,2)
declare @指派数量_Free decimal(16,2)=0   --指派后剩余数量

select @计划数量=计划数量 from [MES_接口_生产计划_生产任务] where 订单编号=@订单号 and 订单行号=@订单行号 and 订单拆分内码=@订单拆分内码

if(@计划数量>@指派数量) 
begin
	set @指派数量_Free =@计划数量-@指派数量  --剩余>0

	declare @拆分内码_New int=0
	--该订单行号已存在未分配的拆分任务，在未分配任务基础上增加未分配数量
	if(select count(1) from [MES_接口_生产计划_生产任务] where 订单编号=@订单号 and 订单行号=@订单行号 and 订单拆分内码<>@订单拆分内码 and isnull(派工状态,0)=0)>0
	begin
		Update [MES_接口_生产计划_生产任务] set [计划数量]=[计划数量]+@指派数量_Free WHERE 订单编号=@订单号 and 订单行号=@订单行号 and isnull(派工状态,0)=0
	end
	else--该订单行号不存在未分配的拆分任务，拆分
	begin
		select @拆分内码_New=max([订单拆分内码])+1 from [MES_接口_生产计划_生产任务] where 订单编号=@订单号 and 订单行号=@订单行号

		INSERT INTO [MES_接口_生产计划_生产任务]
		([订单编号],[订单行号],[订单拆分内码],[物料编码],[物料名称],[基本数量],[计划数量],[已发货数量],[订单发货类型]
		,[仓库代码],[可视订单],[物料类型],[阶段标识],[工序名称],[顺序编号],[性质],[总工时],[行文本备注],[不装配])
		SELECT [订单编号],[订单行号],@拆分内码_New,[物料编码],[物料名称],[基本数量],@指派数量_Free,[已发货数量],[订单发货类型]
		,[仓库代码],[可视订单],[物料类型],[阶段标识],[工序名称],[顺序编号],[性质],[总工时],[行文本备注],[不装配]
		FROM [MES_接口_生产计划_生产任务] WHERE 订单编号=@订单号 and 订单行号=@订单行号 and 订单拆分内码=@订单拆分内码
	end
end
else if(@计划数量<@指派数量) 
begin
	set @指派数量_Free=@计划数量-@指派数量  --剩余<0
	declare @未指派数量_剩余 decimal(16,2)=@指派数量_Free
	if(select count(1) from [MES_接口_生产计划_生产任务] where 订单编号=@订单号 and 订单行号=@订单行号 and 订单拆分内码<>@订单拆分内码 and isnull(派工状态,0)=0)>0
	begin
		select @未指派数量_剩余=计划数量+@指派数量_Free from [MES_接口_生产计划_生产任务] where 订单编号=@订单号 and 订单行号=@订单行号 and 订单拆分内码<>@订单拆分内码 and isnull(派工状态,0)=0
	end

	if(@未指派数量_剩余<0) --剩余<0，报错
		set @ErrMsg='指派数量大于剩余未分配数量，派工失败'
	else if(@未指派数量_剩余=0) --剩余=0，没有未分配数量了，删除未分派任务
	begin
		delete from [MES_接口_生产计划_生产任务] where 订单编号=@订单号 and 订单行号=@订单行号 and 订单拆分内码<>@订单拆分内码 and isnull(派工状态,0)=0
	end
	else   --剩余>0，更新，删除未分派任务
	begin
		update [MES_接口_生产计划_生产任务] set [计划数量] = @未指派数量_剩余 where 订单编号=@订单号 and 订单行号=@订单行号 and 订单拆分内码<>@订单拆分内码 and isnull(派工状态,0)=0
	end
end

if(len(@ErrMsg)=0)
begin
	if(@最晚开始时间='') set @最晚开始时间=NULL
	if(@计划开始时间='') set @计划开始时间=NULL
	if(@计划完成时间='') set @计划完成时间=NULL
	UPDATE [dbo].[MES_接口_生产计划_生产任务]
	   SET [指派对象编号] = @指派对象编号
		  ,[指派对象] = @指派对象
		  ,[计划数量] = @指派数量
		  ,[指派数量] = @指派数量
		  ,[计划开始时间] = @计划开始时间
		  ,[计划完成时间] = @计划完成时间
		  ,[最晚开始时间] = @最晚开始时间
		  ,[派工状态] = 1
		  ,[派工时间] = getdate()
		  ,[任务状态] = 0	--生产任务变为【待执行】状态
		  ,[修改时间] = getdate()
		  ,[派工特殊说明]=@派工特殊说明
		  ,[派工操作人] = @派工操作人
	WHERE [订单编号] = @订单号 AND [订单行号] = @订单行号 and 订单拆分内码=@订单拆分内码
end

select @ErrMsg
GO
/****** Object:  StoredProcedure [dbo].[MES_ProcessManagement_PartGet]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[MES_ProcessManagement_PartGet]
@过滤  NVARCHAR(200)
AS
SELECT top 100 * FROM SAP.SBO_YL.dbo.UBT_OITM where 物料编码 like '' +'%'+@过滤+'%' +''
GO
/****** Object:  StoredProcedure [dbo].[MES_ProcessManagement_ProcessAdd]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[MES_ProcessManagement_ProcessAdd] 
@工艺名称 nvarchar(50) =null
AS

INSERT INTO 基础表_工序 (工艺编号,工序名称)  VALUES((select ISNULL(MAX(工艺编号),0) +1 from 基础表_工序 ),@工艺名称)
select 工艺编号 from 基础表_工序 where 工序名称 = @工艺名称
GO
/****** Object:  StoredProcedure [dbo].[MES_ProcessManagement_ProcessBindGet]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[MES_ProcessManagement_ProcessBindGet]
@物料编号 nvarchar(50)
AS

SELECT *,dbo.基础表_工序.工序名称 as 工艺名称  FROM [车间生产管理工艺_零件工序_工艺库] left join dbo.基础表_工序
 on 车间生产管理工艺_零件工序_工艺库.工艺编号 = dbo.基础表_工序.工艺编号 where 零件图号 = @物料编号 ORDER BY [工艺顺序] 
GO
/****** Object:  StoredProcedure [dbo].[MES_ProcessManagement_ProcessDel]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[MES_ProcessManagement_ProcessDel] 
@工艺编号 int = -1
AS

delete from 基础表_工序 where 工艺编号 = @工艺编号
GO
/****** Object:  StoredProcedure [dbo].[MES_ProcessManagement_ProcessEdit]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[MES_ProcessManagement_ProcessEdit] 
@工艺名称 nvarchar(50) =null,
@工艺编号 int = -1
AS

update 基础表_工序 set 工序名称 = @工艺名称 where 工艺编号 = @工艺编号
GO
/****** Object:  StoredProcedure [dbo].[MES_ProcessManagement_ProcessGet]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[MES_ProcessManagement_ProcessGet]     
@工艺编号 nvarchar(50) = null 
AS 
       
IF @工艺编号 IS NOT NULL AND @工艺编号 != '' 
        -- 将逗号分隔的字符串转换为表值参数        
SELECT 工艺编号 as 工艺编号, 工序名称 as 工艺名称    FROM [基础表_工序]  WHERE 工艺编号 IN (SELECT value FROM STRING_SPLIT(@工艺编号, ',')) 
ELSE     
      
SELECT 工艺编号 as 工艺编号, 工序名称 as 工艺名称    FROM [基础表_工序]  ORDER BY 工艺编号     
GO
/****** Object:  StoredProcedure [dbo].[MES_ProductAdmin_GetRptRecords]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[MES_ProductAdmin_GetRptRecords]
	@rptDate nvarchar(50)='',
	@OPCode nvarchar(50)='',
	@HTCode nvarchar(50)='',
	@OrderNo int=-1,
	@Optor nvarchar(50)='',
	@rptState int=-1	--1未确认，2已确认
AS
declare @whereStr nvarchar(max)=' where [报工日期]='''+Convert(VARCHAR(20),@rptDate)+''''
declare @selStr nvarchar(max)='
	SELECT [AID]
      ,[报工日期]
      ,[班次]
      ,[工位编号]
      ,[工位名称]
      ,[操作人]
      ,[工时类型]
      ,isnull([报工数量],0) as 报工数量
      ,[工时]/60 as 工时
      ,isnull([确认工时],0)/60 as 确认工时
      ,[报工说明]
      ,[报工时间]
      ,a.[合同号]
      ,a.[订单编号]
      ,a.[TaskAID]
      ,[TaskAID_Binding] as 捆绑工序
      ,case when [已确认]=1 then ''已确认'' else ''未确认'' end as 已确认
      ,case when isnull(任务状态,0)=4 then ''已完成'' 
	  when isnull(任务状态,0)=2 then ''已开工'' 
	  when isnull(任务状态,0)=1 and isnull([收料],0)=0 then ''待执行'' 
	  when isnull(任务状态,0)=1 and isnull([收料],0)=1 then ''可执行'' 
	  else '''' end as [任务状态]
	  ,b.物料编号
	  ,b.物料描述
	  ,b.阶段标识
	  ,b.工序名称
  FROM [YL_加工中心_报工记录] a inner join [View_生产订单_MES] b on a.TaskAID=b.TaskAID ';
	if(@OPCode<>'')set @whereStr=@whereStr + ' and [工位编号] = '''+@OPCode+''''
	if(@HTCode<>'')set @whereStr=@whereStr + ' and a.[合同号] like ''%'+@HTCode+'%'''
	if(@OrderNo>0)set @whereStr=@whereStr + ' and a.[订单编号]='+Convert(VARCHAR(10),@OrderNo)
	if(@Optor<>'')set @whereStr=@whereStr + ' and [操作人] like ''%'+@Optor+'%'''
	if(@rptState>0)set @whereStr=@whereStr + ' and isnull([已确认],0)='+Convert(VARCHAR(10),@rptState)

	set @selStr=@selStr+@whereStr+' order by [报工日期],[报工时间],[订单编号],[TaskAID]'
print @selStr
EXEC sp_executesql @selStr
GO
/****** Object:  StoredProcedure [dbo].[MES_ProductAdmin_Query]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[MES_ProductAdmin_Query]
@订单号 int=0,
@物料类型 nvarchar(50)='自制件',   --自制件、装配件
@合同号 nvarchar(50)='',
@产品编码  nvarchar(50)='',
@产品名称  nvarchar(50)='',
@工序名称  nvarchar(50)='',
@性质  nvarchar(50)='',
@要求完工日期1  nvarchar(50)='',
@要求完工日期2  nvarchar(50)='',
@排产状态  nvarchar(50)='全部',   --全部，已完成、未完成
@工位 nvarchar(500)=''
AS
declare @selectStr nvarchar(4000)
declare @selectStrWhere nvarchar(4000)=' where [物料类型]=''pit_Resource'''
if(@物料类型='自制件')   --自制件
	set @selectStr='
		SELECT top 100 isnull([不合格数量],0) as 不合格数量, [收料数量],[合同号],[订单编号] as 订单号,[订单行号],[订单拆分内码] as 拆分内码,[物料编号] as 产品编码,[物料描述] as 产品名称,[计划数量],[计划完成] as 要求完工日期,[工序名称],[加急状态],性质,总工时,[占用情况]
		,[排产状态],[工序计划数量],指派对象编号,指派对象,指派数量,计划开始时间,计划完成时间,最晚开始时间,[派工状态],[外协通知]
		,[优先级],[未完成说明],[序检],isnull([测试],0) as [测试],isnull([入库],0) as [入库],TaskAID
		FROM [View_生产订单_MES]'
else   --装配件
	set @selectStr='
		SELECT top 100 isnull([不合格数量],0) as 不合格数量, [收料数量], [合同号],[订单编号] as 订单号,[订单行号],[订单拆分内码] as 拆分内码,[物料编号] as 产品编码,[物料描述] as 产品名称,[计划数量],'''' as 合同交货期,[计划完成] as 预计齐套时间,''齐'' as 是否齐套,'''' as 齐套检测,''是'' as 齐套锁料,[计划开始] as 备料日期,0 as 加急状态,1000 as 总工时,[工序名称],[加急状态],性质,总工时,[占用情况]
		,[排产状态],[工序计划数量],指派对象编号,指派对象,指派数量,计划开始时间,计划完成时间,最晚开始时间,[派工状态],[外协通知]
		,[优先级],[未完成说明],[派工特殊说明],[最后编辑人],[最后编辑时间],TaskAID
		FROM [View_生产订单_MES]'


if(@订单号>0)set @selectStrWhere=@selectStrWhere + ' and [订单编号]='+Convert(VARCHAR(10),@订单号)
if(@合同号<>'')set @selectStrWhere=@selectStrWhere + ' and [合同号] like ''%'+@合同号+'%'''
if(@产品编码<>'')set @selectStrWhere=@selectStrWhere + ' and [物料编号] like ''%'+@产品编码+'%'''
if(@产品名称<>'')set @selectStrWhere=@selectStrWhere + ' and [物料描述] like ''%'+@产品名称+'%'''
if(@工序名称<>'')set @selectStrWhere=@selectStrWhere + ' and [工序名称] = '''+@工序名称+''''
if(@性质<>'')set @selectStrWhere=@selectStrWhere + ' and [性质] = '''+@性质+''''
if(@要求完工日期1 <>'')set @selectStrWhere=@selectStrWhere + ' and [计划完成] >= '''+@要求完工日期1+''''
if(@要求完工日期2 <>'')set @selectStrWhere=@selectStrWhere + ' and [计划完成] <= '''+@要求完工日期2+''''
if(@排产状态='未完成')set @selectStrWhere=@selectStrWhere + ' and isnull([排产状态],0) = 0'
else if(@排产状态='已完成')set @selectStrWhere=@selectStrWhere + ' and [排产状态] = 1'
if(@物料类型='自制件') set @selectStrWhere=@selectStrWhere + ' and [不装配] <> ''否'''
if(@物料类型='装配件') set @selectStrWhere=@selectStrWhere + ' and [不装配] = ''否'''
if(@工位<>'') set @selectStrWhere=@selectStrWhere + ' and [指派对象编号] in ( SELECT value FROM STRING_SPLIT('''+ @工位 +''', '',''))'

set @selectStr=@selectStr+@selectStrWhere
print @selectStr
EXEC sp_executesql @selectStr
GO
/****** Object:  StoredProcedure [dbo].[MES_ProductAdmin_RptConfirm]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[MES_ProductAdmin_RptConfirm]
	@rptAID int,
	@confirmTime int,
	@confirm_desc nvarchar(2000),
	@Optor nvarchar(50)
AS
BEGIN
	declare @词条名称 nvarchar(50)='已确认'
	declare @数据类别 nvarchar(50)='报工确认'
	declare @词条ID int=-1
	select @词条ID=词条编号 from YL_基础表_数据字典 where 词条名称=@词条名称 and 数据类别=@数据类别

	update YL_加工中心_报工记录 set 确认工时=@confirmTime,报工说明=@confirm_desc,已确认=@词条ID,确认人=@Optor,确认时间=getdate() where AID=@rptAID
END
GO
/****** Object:  StoredProcedure [dbo].[MES_ProductCenter_DoingTask]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[MES_ProductCenter_DoingTask]
	@指派对象编号 nvarchar(50)
AS
BEGIN
	if(select count(1) from [View_生产订单_MES] where 指派对象编号=@指派对象编号 and 加工状态=1)>0
		select top(1) * from [View_生产订单_MES] where 指派对象编号=@指派对象编号 and 加工状态=1 order by 操作时间 desc
	else
		select top(1) * from [View_生产订单_MES] where 指派对象编号=@指派对象编号 and 任务状态=2 order by 开工时间 desc
END
GO
/****** Object:  StoredProcedure [dbo].[MES_ProductCenter_GetOrderTasks]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[MES_ProductCenter_GetOrderTasks]
	@TaskAID bigint
AS
BEGIN
declare @订单编号 int=-1
declare @订单行号 int=-1
select @订单编号=[订单编号],@订单行号 = 订单行号 FROM [View_生产订单_MES] where TaskAID=@TaskAID

  SELECT [订单编号]
      ,[合同号]
	  ,[订单行号]
      ,[物料编号]
      ,[物料描述]
      ,[阶段标识]
      ,[工序名称]
      ,[顺序编号]
      ,[指派对象编号]
      ,[指派对象]
      ,isnull([指派数量],0) as [指派数量]
      ,[计划开始时间]
      ,[计划完成时间]
      ,[订单拆分内码]
      ,isnull([收料数量],0) as [收料数量]
      ,isnull([完成数量],0) as [完成数量]
      ,Convert(nvarchar(50),isnull([进度],0))+'%' as [进度]
      ,[TaskAID]
      ,[开工时间]
      ,[完工时间]
      ,case 
	  --when isnull(任务状态,0)=4 then '已完成' 
	  when isnull(任务状态,0)=2 then '已开工' 
	  --when isnull(任务状态,0)=0 then '待执行' 
	  --when isnull(任务状态,0)=1 then '可执行' 
	  else '''' end as [任务状态]
      -- 新增：前序不合格数
      ,ISNULL((
          SELECT SUM(ISNULL(不合格数, 0)) 
          FROM [dbo].[YL_质量检验_质检记录] qc
          INNER JOIN [View_生产订单_MES] vt ON qc.TaskAID = vt.TaskAID
          WHERE vt.[订单编号] = vo.[订单编号] 
            AND vt.[订单行号] < vo.[订单行号]
			AND qc.检测类型编号 = '6'
      ), 0) as [前序不合格数]
	  ,ISNULL((
          SELECT SUM(ISNULL(合格数, 0)) 
          FROM [dbo].[YL_质量检验_质检记录] qc
          INNER JOIN [View_生产订单_MES] vt ON qc.TaskAID = vt.TaskAID
          WHERE vt.[订单编号] = vo.[订单编号] 
            AND vt.[订单行号] = vo.[订单行号]-1
			AND qc.检测类型编号 = '6'
      ), 0) as [上序合格数]
  FROM [View_生产订单_MES] vo
  where [订单编号]=@订单编号 
  order by [订单行号]
END
GO
/****** Object:  StoredProcedure [dbo].[MES_ProductCenter_GetTask]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[MES_ProductCenter_GetTask]
	@TaskAID int =-1,
    @订单号 int = -1,
    @零件编号 nvarchar(50) = '',
    @计划开工_Start nvarchar(50) = '',
    @计划开工_End nvarchar(50) = '',
    @生产状态 int = -1,	-- -1: 未指定；0: 待执行；1: 可执行；2: 已开工；4: 已完工
    @工位名称 nvarchar(50) = '',
	@用户ID nvarchar(50) = '',
	@计划号 nvarchar(50) = '',
	@销售订单 nvarchar(50) = ''
AS
BEGIN
    DECLARE @whereStr nvarchar(max) = ' WHERE 排产状态 = 1 '
    DECLARE @selStr nvarchar(max) = 
    'SELECT TaskAID,
            [订单编号] as 订单号,
			合同号,
			加急总数,
			派工特殊说明,
            [订单拆分内码],
            [订单行号],
            [开工时间],
            [物料编号] as 零件编码,
            [物料描述] as 零件名称,
            case when isnull([加急状态],0)=1 then ''加急'' else ''否'' end as [加急],
            [优先级] as [优先],
            [指派对象编号],
            [指派对象],
            [工序名称],
			[二次派工],
			[计划号],
            isnull([指派数量],0) as 分配数,
            [计划开始时间] as 计划开始,
            [计划完成时间] as 计划完成,
            [最晚开始时间] as 最晚开始,
            isnull([收料数量],0) as 收料,
            isnull([完成数量],0) as 完成数量,
			case 
                when isnull(齐套,0)=1 then ''是'' 
                when isnull(齐套,0)=0 then ''否''
			end as [齐套],
			case 
                when isnull(发料状态,0)=1 then ''发料齐套'' 
                when isnull(发料状态,0)=2 then ''发料缺件''
			end as [发料状态],
			case 
                when isnull(拣配状态,0)=1 then ''已拣配'' 
                when isnull(拣配状态,0)=0 then ''未拣配''
			end as [拣配状态],
            case 
                when isnull(任务状态,0)=4 then ''已完成'' 
                when isnull(任务状态,0)=2 then ''已开工'' 
                when isnull(任务状态,0)=0 then ''待执行'' 
                when isnull(任务状态,0)=1 then ''可执行''
                else '''' 
            end as [任务状态],
            case 
                when isnull(加工状态,0)=2 then ''辅助开始''
                when isnull(加工状态,0)=3 then ''辅助结束''
                when isnull(加工状态,0)=4 then ''开始加工''
                when isnull(加工状态,0)=5 then ''暂停''
                when isnull(加工状态,0)=6 then ''报工''
                else '''' 
            end as [加工状态],
            isnull(加工状态,0) as 加工状态编号,
            case when isnull([首检],-1)=1 then ''OK'' when isnull([首检],-1)=0 then ''NG'' else '''' end as [首检],
            case when isnull([序检],-1)=1 then ''OK'' when isnull([序检],-1)=0 then ''NG'' else '''' end as [序检],
            -- 新增：下序名称
            (SELECT TOP 1 [工序名称] 
             FROM [View_生产订单_MES] AS next_task 
             WHERE next_task.[订单编号] = main.[订单编号] 
               AND next_task.[订单行号] = main.[订单行号] + 1
               AND next_task.[排产状态] = 1
             ORDER BY next_task.[订单行号]) AS 下序名称,
			 (
                   SELECT ISNULL(SUM(ISNULL(a.合格数, 0)), 0)
                   FROM [dbo].[YL_质量检验_质检记录] as a 
                   INNER JOIN [dbo].[MES_接口_生产计划_生产任务] as b ON a.TaskAID = b.AID
                   WHERE b.订单编号 = main.[订单编号] 
                     AND b.订单行号 = main.[订单行号] - 1
					 AND a.检测类型编号 = 6
               ) as 上序合格数,
			   (
				SELECT STRING_AGG(a.Personnel_Name, '','') 
				FROM [dbo].[登录基础数据_人员信息] AS a 
				WHERE EXISTS (
					SELECT 1 
					FROM [dbo].[MES_接口_生产计划_生产任务] AS b 
					WHERE b.订单编号 = main.订单编号 
					  AND b.订单行号 = main.订单行号
					  AND EXISTS (
						  SELECT 1 
						  FROM STRING_SPLIT(b.二次派工, '','') AS ids
						  WHERE LTRIM(RTRIM(ids.value)) = CAST(a.Personnel_Number AS VARCHAR(50))
					  )
				)
			) as 二次派工名称
     FROM [View_生产订单_MES] AS main'

    -- 基础过滤：排除外协
    SET @whereStr = @whereStr + ' AND [指派对象] <> ''外协'' AND [指派对象] NOT LIKE ''%装配%'''

    -- 订单号
    IF (@订单号 > 0)
        SET @whereStr = @whereStr + ' AND [订单编号] = ' + CONVERT(VARCHAR(10), @订单号)
	IF (@计划号 > 0)
        SET @whereStr = @whereStr + ' AND [计划号] = '''+@计划号+'''' 
	IF (@销售订单<> '')
        SET @whereStr = @whereStr + ' AND [合同号] LIKE ''%' + @销售订单 + '%''' 
	IF (@TaskAID > 0)
        SET @whereStr = @whereStr + ' AND [TaskAID] = ' + CONVERT(VARCHAR(10), @TaskAID)
    -- 零件编号（模糊）
    IF (@零件编号 <> '')
        SET @whereStr = @whereStr + ' AND [物料编号] LIKE ''%' + @零件编号 + '%'''

    -- 计划开工时间范围
    IF (@计划开工_Start <> '')
        SET @whereStr = @whereStr + ' AND [计划开始时间] >= ''' + @计划开工_Start + ''''
    IF (@计划开工_End <> '')
        SET @whereStr = @whereStr + ' AND [计划开始时间] <= ''' + @计划开工_End + ''''

    -- 工位名称（支持逗号分隔的多值）
    IF (@工位名称 <> '')
    BEGIN
        -- 转义单引号防止注入（虽然 STRING_SPLIT 不直接拼接值，但安全起见）
        SET @whereStr = @whereStr + 
            ' AND [指派对象] IN (SELECT LTRIM(RTRIM(value)) FROM STRING_SPLIT(''' + REPLACE(@工位名称, '''', '''''') + ''', '',''))'
    END

    -- 生产状态逻辑（核心修复点）
    IF (@生产状态 IS NULL OR @生产状态 = -1)
    BEGIN
	    print @生产状态
        -- 未指定状态：只查 1（可执行）、2（已开工）
        SET @whereStr = @whereStr + ' AND ISNULL(任务状态, 0) IN (0,1,2) '
    END
    ELSE IF (@生产状态 = 0)
    BEGIN
        SET @whereStr = @whereStr + ' AND ISNULL(任务状态, 0) = 0 ' -- 待执行
    END
    ELSE IF (@生产状态 = 1)
    BEGIN
        SET @whereStr = @whereStr + ' AND ISNULL(任务状态, 0) = 1 ' -- 可执行
    END
    ELSE IF (@生产状态 = 2)
    BEGIN
        SET @whereStr = @whereStr + ' AND ISNULL(任务状态, 0) = 2 ' -- 已开工
    END
    ELSE IF (@生产状态 = 4)
    BEGIN
        SET @whereStr = @whereStr + ' AND ISNULL(任务状态, 0) = 4 ' -- 已完工
    END

    -- 用户ID不为空时的并集条件
    IF (@用户ID <> '')
	BEGIN
		SET @whereStr = @whereStr + ' OR ([排产状态] = 1 AND EXISTS (
			SELECT 1 FROM STRING_SPLIT([二次派工], '','') 
			WHERE LTRIM(RTRIM(value)) = ''' + @用户ID + '''
		))'
	END

    -- 拼接最终语句
    SET @selStr = @selStr + @whereStr + ' ORDER BY [计划开始时间], [订单编号], [阶段标识]'

    -- 调试用（上线前可注释掉）
    PRINT @selStr

    EXEC sp_executesql @selStr
	
END
GO
/****** Object:  StoredProcedure [dbo].[MES_ProductCenter_GetTask_zp]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[MES_ProductCenter_GetTask_zp]
	@TaskAID int =-1,
    @订单号 int = -1,
    @零件编号 nvarchar(50) = '',
    @计划开工_Start nvarchar(50) = '',
    @计划开工_End nvarchar(50) = '',
    @生产状态 int = -1,	-- -1: 未指定；0: 待执行；1: 可执行；2: 已开工；4: 已完工
    @工位名称 nvarchar(50) = '',
	@用户ID nvarchar(50) = '',
	@计划号 nvarchar(50) = '',
	@销售订单 nvarchar(50) = ''
AS
BEGIN
    DECLARE @whereStr nvarchar(max) = ' WHERE 排产状态 = 1 '
    DECLARE @selStr nvarchar(max) = 
    'SELECT TaskAID,
            [订单编号] as 订单号,
			合同号,
			自制件属性,
			加急总数,
			派工特殊说明,
            [订单拆分内码],
            [订单行号],
            [开工时间],
            [物料编号] as 零件编码,
            [物料描述] as 零件名称,
            case when isnull([加急状态],0)=1 then ''加急'' else ''否'' end as [加急],
            [优先级] as [优先],
            [指派对象编号],
            [指派对象],
            [工序名称],
			[二次派工],
			[计划号],
            isnull([指派数量],0) as 分配数,
            [计划开始时间] as 计划开始,
            [计划完成时间] as 计划完成,
            [最晚开始时间] as 最晚开始,
            isnull([收料数量],0) as 收料,
            isnull([完成数量],0) as 完成数量,
			case 
                when isnull(齐套,0)=1 then ''是'' 
                when isnull(齐套,0)=0 then ''否''
			end as [齐套],
			case 
                when isnull(发料状态,0)=1 then ''发料齐套'' 
                when isnull(发料状态,0)=2 then ''发料缺件''
			end as [发料状态],
			case 
                when isnull(拣配状态,0)=1 then ''已拣配'' 
                when isnull(拣配状态,0)=0 then ''未拣配''
			end as [拣配状态],
            case 
                when isnull(任务状态,0)=4 then ''已完成'' 
                when isnull(任务状态,0)=2 then ''已开工'' 
                when isnull(任务状态,0)=0 then ''待执行'' 
                when isnull(任务状态,0)=1 then ''可执行''
                else '''' 
            end as [任务状态],
            case 
                when isnull(加工状态,0)=2 then ''辅助开始''
                when isnull(加工状态,0)=3 then ''辅助结束''
                when isnull(加工状态,0)=4 then ''开始加工''
                when isnull(加工状态,0)=5 then ''暂停''
                when isnull(加工状态,0)=6 then ''报工''
                else '''' 
            end as [加工状态],
            isnull(加工状态,0) as 加工状态编号,
            case when isnull([首检],-1)=1 then ''OK'' when isnull([首检],-1)=0 then ''NG'' else '''' end as [首检],
            case when isnull([序检],-1)=1 then ''OK'' when isnull([序检],-1)=0 then ''NG'' else '''' end as [序检],
            -- 新增：下序名称
            (SELECT TOP 1 [工序名称] 
             FROM [View_生产订单_MES] AS next_task 
             WHERE next_task.[订单编号] = main.[订单编号] 
               AND next_task.[订单行号] = main.[订单行号] + 1
               AND next_task.[排产状态] = 1
             ORDER BY next_task.[订单行号]) AS 下序名称,
			 (
                   SELECT ISNULL(SUM(ISNULL(a.合格数, 0)), 0)
                   FROM [dbo].[YL_质量检验_质检记录] as a 
                   INNER JOIN [dbo].[MES_接口_生产计划_生产任务] as b ON a.TaskAID = b.AID
                   WHERE b.订单编号 = main.[订单编号] 
                     AND b.订单行号 = main.[订单行号] - 1
					 AND a.检测类型编号 = 6
               ) as 上序合格数,
			   (
				SELECT STRING_AGG(a.Personnel_Name, '','') 
				FROM [dbo].[登录基础数据_人员信息] AS a 
				WHERE EXISTS (
					SELECT 1 
					FROM [dbo].[MES_接口_生产计划_生产任务] AS b 
					WHERE b.订单编号 = main.订单编号 
					  AND b.订单行号 = main.订单行号
					  AND EXISTS (
						  SELECT 1 
						  FROM STRING_SPLIT(b.二次派工, '','') AS ids
						  WHERE LTRIM(RTRIM(ids.value)) = CAST(a.Personnel_Number AS VARCHAR(50))
					  )
				)
			) as 二次派工名称
     FROM [View_生产订单_MES] AS main'

    -- 基础过滤：排除外协
    SET @whereStr = @whereStr + ' AND [指派对象] <> ''外协'' AND [指派对象] LIKE ''%装配%'''

    -- 订单号
    IF (@订单号 > 0)
        SET @whereStr = @whereStr + ' AND [订单编号] = ' + CONVERT(VARCHAR(10), @订单号)
	IF (@计划号 > 0)
        SET @whereStr = @whereStr + ' AND [计划号] = '''+@计划号+'''' 
	IF (@销售订单<> '')
        SET @whereStr = @whereStr + ' AND [合同号] LIKE ''%' + @销售订单 + '%''' 
	IF (@TaskAID > 0)
        SET @whereStr = @whereStr + ' AND [TaskAID] = ' + CONVERT(VARCHAR(10), @TaskAID)
    -- 零件编号（模糊）
    IF (@零件编号 <> '')
        SET @whereStr = @whereStr + ' AND [物料编号] LIKE ''%' + @零件编号 + '%'''

    -- 计划开工时间范围
    IF (@计划开工_Start <> '')
        SET @whereStr = @whereStr + ' AND [计划开始时间] >= ''' + @计划开工_Start + ''''
    IF (@计划开工_End <> '')
        SET @whereStr = @whereStr + ' AND [计划开始时间] <= ''' + @计划开工_End + ''''

    -- 工位名称（支持逗号分隔的多值）
    IF (@工位名称 <> '')
    BEGIN
        -- 转义单引号防止注入（虽然 STRING_SPLIT 不直接拼接值，但安全起见）
        SET @whereStr = @whereStr + 
            ' AND [指派对象] IN (SELECT LTRIM(RTRIM(value)) FROM STRING_SPLIT(''' + REPLACE(@工位名称, '''', '''''') + ''', '',''))'
    END

    -- 生产状态逻辑（核心修复点）
    IF (@生产状态 IS NULL OR @生产状态 = -1)
    BEGIN
	    print @生产状态
        -- 未指定状态：只查 1（可执行）、2（已开工）
        SET @whereStr = @whereStr + ' AND ISNULL(任务状态, 0) IN (0,1,2) '
    END
    ELSE IF (@生产状态 = 0)
    BEGIN
        SET @whereStr = @whereStr + ' AND ISNULL(任务状态, 0) = 0 ' -- 待执行
    END
    ELSE IF (@生产状态 = 1)
    BEGIN
        SET @whereStr = @whereStr + ' AND ISNULL(任务状态, 0) = 1 ' -- 可执行
    END
    ELSE IF (@生产状态 = 2)
    BEGIN
        SET @whereStr = @whereStr + ' AND ISNULL(任务状态, 0) = 2 ' -- 已开工
    END
    ELSE IF (@生产状态 = 4)
    BEGIN
        SET @whereStr = @whereStr + ' AND ISNULL(任务状态, 0) = 4 ' -- 已完工
    END

    -- 用户ID不为空时的并集条件
    IF (@用户ID <> '')
	BEGIN
		SET @whereStr = @whereStr + ' OR ([排产状态] = 1 AND EXISTS (
			SELECT 1 FROM STRING_SPLIT([二次派工], '','') 
			WHERE LTRIM(RTRIM(value)) = ''' + @用户ID + '''
		))'
	END

    -- 拼接最终语句
    SET @selStr = @selStr + @whereStr + ' ORDER BY [计划开始时间], [订单编号], [阶段标识]'

    -- 调试用（上线前可注释掉）
    PRINT @selStr

    EXEC sp_executesql @selStr
	
END
GO
/****** Object:  StoredProcedure [dbo].[MES_ProductCenter_OptRecord_Save]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[MES_ProductCenter_OptRecord_Save]
    @dicItemName nvarchar(50)='收料',
    @dataType nvarchar(50)='生产操作',
    @TaskAID bigint,
    @optCount int=null,
    @optDescription nvarchar(50)='',
    @optor nvarchar(50)='',
    @optTime datetime,
	@selectedOperators NVARCHAR(50) = NULL,
	@是否休息日 bit = 0,           -- 新增参数
    @是否法定休息日 bit = 0        -- 新增参数
AS
BEGIN
    SET NOCOUNT ON;
    
    -- 原有变量声明
    declare @dicItemID int
    declare @HTCode nvarchar(50)
    declare @OrderNo int
    declare @PartCode nvarchar(50)
    declare @PartName nvarchar(50)
    declare @OPCode nvarchar(50)
    declare @OPName nvarchar(50)
    declare @StageFlag nvarchar(50)
    declare @ProcessName nvarchar(50)
    declare @AssembleType nvarchar(50)
    
    -- 新增用于工时计算的变量
    declare @cycleStartTime datetime
    declare @cycleEndTime datetime
    declare @totalWorkSeconds int = 0
    
    select @dicItemID=词条编号 from YL_基础表_数据字典 where 词条名称=@dicItemName and 数据类别=@dataType
    select @HTCode=[合同号],@OrderNo=[订单编号],@OPCode=[指派对象编号],@OPName=[指派对象],@PartCode=[物料编号],@PartName=[物料描述],@StageFlag=[阶段标识],@ProcessName=[工序名称],@AssembleType=[不装配]
    from View_生产订单_MES where TaskAID=@TaskAID
    
    -- 插入操作记录
    INSERT INTO [dbo].[YL_加工中心_操作记录表]
           ([操作类别编号]
           ,[操作类别]
           ,[阶段标识]
           ,[工序名称]
           ,[工位编号]
           ,[工位名称]
           ,[操作人]
           ,[合同号]
           ,[订单编号]
           ,[物料编号]
           ,[物料描述]
           ,[操作数值]
           ,[操作内容]
           ,[操作描述]
           ,TaskAID
           ,[开始时间]
           ,[不装配]
		   ,最后编辑时间)
    Values(@dicItemID
          ,@dicItemName
          ,@StageFlag
          ,@ProcessName
          ,@OPCode
          ,@OPName
          ,@optor
          ,@HTCode
          ,@OrderNo
          ,@PartCode
          ,@PartName
          ,@optCount
          ,@dicItemName
          ,@optDescription
          ,@TaskAID
          ,@optTime
          ,@AssembleType
		  ,@optTime
        )
    
    -- 获取刚插入的记录ID
    declare @currentRecordAID int = SCOPE_IDENTITY()
    
    -- 处理暂停操作
    if(@dicItemName='暂停')
    begin
        -- 查找最近的一个开始加工或辅助开始记录
        declare @lastStartRecordAID int = 0
        declare @lastStartTime datetime
        declare @lastOperationType nvarchar(50)
        
        select top(1) 
            @lastStartRecordAID = AID, 
            @lastStartTime = 开始时间,
            @lastOperationType = 操作类别
        from [YL_加工中心_操作记录表]
        where TaskAID = @TaskAID 
          and 工位名称 = @OPName 
          and 操作类别 in ('开始加工', '辅助开始')
          and AID < @currentRecordAID
        order by 开始时间 desc
        
        if(@lastStartRecordAID > 0)
        begin
            declare @workTimeBeforePause int = DATEDIFF(SECOND, @lastStartTime, @optTime)
            
            update [YL_加工中心_操作记录表] 
            set 
                结束时间 = @optTime,
                实际工时 = @workTimeBeforePause
            where AID = @lastStartRecordAID
            
            update [YL_加工中心_操作记录表] 
            set 
                关联开始记录ID = @lastStartRecordAID,
                关联操作类型 = @lastOperationType
            where AID = @currentRecordAID
        end
    end
    
    -- 处理开始加工/辅助开始操作
    if(@dicItemName in ('开始加工', '辅助开始'))
    begin
        declare @lastPauseRecordAID int = 0
        declare @lastPauseTime datetime
        declare @lastPauseOperationType nvarchar(50)
        
        select top(1) 
            @lastPauseRecordAID = AID, 
            @lastPauseTime = 开始时间,
            @lastPauseOperationType = 关联操作类型
        from [YL_加工中心_操作记录表]
        where TaskAID = @TaskAID 
          and 工位名称 = @OPName 
          and 操作类别 = '暂停'
          and 结束时间 IS NULL
          and AID < @currentRecordAID
        order by 开始时间 desc
        
        if(@lastPauseRecordAID > 0)
        begin
            declare @pauseDuration int = DATEDIFF(SECOND, @lastPauseTime, @optTime)
            
            update [YL_加工中心_操作记录表] 
            set 
                关联暂停记录ID = @lastPauseRecordAID,
                暂停时间 = @lastPauseTime
            where AID = @currentRecordAID
            
            update [YL_加工中心_操作记录表] 
            set 
                结束时间 = @optTime,
                暂停时长 = @pauseDuration
            where AID = @lastPauseRecordAID
        end
    end
    
    -- 处理报工和辅助结束操作
    if(@dicItemName in ('报工', '辅助结束'))
    begin
        declare @cycleStartRecordAID int = 0
        declare @totalWorkTime int = 0
        declare @totalPauseTime int = 0
        declare @actualWorkTime int = 0
        
        declare @lastEndRecordAID int = 0
        declare @lastEndTime datetime
        
        -- 获取上次报工或辅助结束记录
        select top(1) 
            @lastEndRecordAID = AID, 
            @lastEndTime = 结束时间
        from [YL_加工中心_操作记录表]
        where TaskAID = @TaskAID 
          and 工位名称 = @OPName 
          and 操作类别 = @dicItemName
          and AID < @currentRecordAID
        order by 结束时间 desc
        
        -- 确定周期开始记录
        if(@lastEndRecordAID > 0)
        begin
            -- 上次操作之后开始的新周期
            if(@dicItemName = '报工')
            begin
                select top(1) 
                    @cycleStartRecordAID = AID, 
                    @cycleStartTime = 开始时间
                from [YL_加工中心_操作记录表]
                where TaskAID = @TaskAID 
                  and 工位名称 = @OPName 
                  and 操作类别 = '开始加工'
                  and 开始时间 > @lastEndTime
                  and AID < @currentRecordAID
                order by 开始时间 asc
            end
            else if(@dicItemName = '辅助结束')
            begin
                select top(1) 
                    @cycleStartRecordAID = AID, 
                    @cycleStartTime = 开始时间
                from [YL_加工中心_操作记录表]
                where TaskAID = @TaskAID 
                  and 工位名称 = @OPName 
                  and 操作类别 = '辅助开始'
                  and 开始时间 > @lastEndTime
                  and AID < @currentRecordAID
                order by 开始时间 asc
            end
        end
        else
        begin
            -- 第一次操作，从最早记录开始
            if(@dicItemName = '报工')
            begin
                select top(1) 
                    @cycleStartRecordAID = AID, 
                    @cycleStartTime = 开始时间
                from [YL_加工中心_操作记录表]
                where TaskAID = @TaskAID 
                  and 工位名称 = @OPName 
                  and 操作类别 = '开始加工'
                  and AID < @currentRecordAID
                order by 开始时间 asc
            end
            else if(@dicItemName = '辅助结束')
            begin
                select top(1) 
                    @cycleStartRecordAID = AID, 
                    @cycleStartTime = 开始时间
                from [YL_加工中心_操作记录表]
                where TaskAID = @TaskAID 
                  and 工位名称 = @OPName 
                  and 操作类别 = '辅助开始'
                  and AID < @currentRecordAID
                order by 开始时间 asc
            end
        end
        
        if(@cycleStartRecordAID > 0)
        begin
            set @cycleEndTime = @optTime
            set @totalWorkTime = DATEDIFF(SECOND, @cycleStartTime, @optTime)
            
            -- 计算该周期内的暂停时间（用于设备时间计算）
            select @totalPauseTime = ISNULL(SUM(暂停时长), 0)
            from [YL_加工中心_操作记录表]
            where TaskAID = @TaskAID 
              and 工位名称 = @OPName 
              and 操作类别 = '暂停'
              and 开始时间 >= @cycleStartTime
              and 结束时间 <= @optTime
              and 暂停时长 IS NOT NULL
            
            set @actualWorkTime = @totalWorkTime - @totalPauseTime
            set @totalWorkSeconds = @totalWorkTime  -- 人员工时使用总时长，不考虑暂停
            
            -- 更新操作记录的汇总数据
            update [YL_加工中心_操作记录表] 
            set 
                关联开始记录ID = @cycleStartRecordAID,
                开始时间 = @cycleStartTime,
                结束时间 = @optTime,
                总时长 = @totalWorkTime,          -- 总时长（秒）
                暂停总时长 = @totalPauseTime,     -- 暂停总时长（秒）
                实际工时 = @actualWorkTime         -- 实际工时 = 总时长 - 暂停总时长（秒）
            where AID = @currentRecordAID
            
             -- ⭐ 只有在非休息日时才计算人员工时
            IF (@是否休息日 = 0 AND @是否法定休息日 = 0)
            BEGIN
                exec dbo.计算人员工时 @TaskAID, @currentRecordAID, @OPName, @cycleStartTime, @cycleEndTime, @totalWorkSeconds,
                     @HTCode, @OrderNo, @PartCode, @PartName, @OPCode, @ProcessName, @dicItemName, @optor,@selectedOperators 
            END
            ELSE
            BEGIN
                -- 休息日加班：只记录设备工时，不计算人员工时
                UPDATE [YL_加工中心_操作记录表] 
                SET 操作描述 = ISNULL(操作描述, '') + '【休息日/法定休息日加班，设备运转，不计算人员工时】'
                WHERE AID = @currentRecordAID
            END
        end
    end

END
GO
/****** Object:  StoredProcedure [dbo].[MES_ProductCenter_OptRecords]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[MES_ProductCenter_OptRecords]
	@OPCode nvarchar(50),
	@OrderNo int=-1,
	@PartCode nvarchar(50)='',
	@PlanStart datetime=null,
	@PlanEnd datetime=null,
	@OptType nvarchar(50)=''
AS
BEGIN
declare @whereString nvarchar(max)=' where 工位编号='''+@OPCode+''''
declare @orderString nvarchar(max)=' order by 开始时间 desc'
declare @sqlString nvarchar(max)='
SELECT TOP(50) [操作类别]
      ,[工位编号]
      ,[工位名称]
      ,[操作人]
      ,[合同号]
      ,[订单编号]
      ,[物料编号]
      ,[物料描述]
      ,[操作数值]
      ,[操作内容]
      ,[操作描述]
      ,[TaskAID]
      ,[开始时间]
      ,[结束时间]
      ,[工时]/60 as [工时]
FROM [YL_加工中心_操作记录表]';

if(@OrderNo>0) set @whereString=@whereString+' and [订单编号]='+Convert(VARCHAR(10),@OrderNo)
if(len(@PartCode)>0) set @whereString=@whereString+' and [物料编号] like ''%'+@PartCode+'%'''
if(len(@PlanStart)>0) set @whereString=@whereString+' and [开始时间] >= '''+Convert(VARCHAR(50),@PlanStart)+''''
if(len(@PlanEnd)>0) set @whereString=@whereString+' and [开始时间] <= '''+Convert(VARCHAR(50),DATEADD(day,1, @PlanEnd))+''''
if(len(@OptType)>0) set @whereString=@whereString+' and [操作类别] = '''+@OptType+''''

set @sqlString=@sqlString+@whereString+@orderString
print @sqlString
EXEC sp_executesql @sqlString

END
GO
/****** Object:  StoredProcedure [dbo].[MES_ProductTask_Excutable]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[MES_ProductTask_Excutable]
	@TaskAID bigint
AS
declare @操作时间 datetime=getdate()
BEGIN
	--更新收料数量、收料状态、可执行状态
	Update MES_接口_生产计划_生产任务 set 可执行=1, 修改时间=@操作时间 where AID=@TaskAID
END
GO
/****** Object:  StoredProcedure [dbo].[MES_ProductTask_FirstCheck]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[MES_ProductTask_FirstCheck]
	@TaskAID bigint,
	@checkResult int,
	@optor nvarchar(50)
AS
BEGIN
	declare @操作时间 datetime=getdate();
	declare @词条名称 nvarchar(50)='首检'
	declare @数据类别 nvarchar(50)='生产操作'
	declare @词条ID int=-1
	select @词条ID=词条编号 from YL_基础表_数据字典 where 词条名称=@词条名称 and 数据类别=@数据类别
	--更新首检，首检时间
	Update MES_接口_生产计划_生产任务 set 首检=@checkResult where AID=@TaskAID 

	--生成操作记录
	EXEC [dbo].[MES_ProductCenter_OptRecord_Save]
		@dicItemName = @词条名称,
		@dataType = @数据类别,
		@TaskAID = @TaskAID,
		@optCount = @checkResult,  --操作数值
		--@optDescription = @helfDescription,
		@optor = @optor,
		@optTime = @操作时间
END
GO
/****** Object:  StoredProcedure [dbo].[MES_ProductTask_HelpEnd]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	辅助结束存储过程（整合加班逻辑）
-- =============================================
CREATE PROCEDURE [dbo].[MES_ProductTask_HelpEnd]
	@TaskAID bigint,
	@partCount int,
	@optor nvarchar(50),
	@指派数量 decimal(16,2)=-1,
	@selectedOperators NVARCHAR(50) = NULL,
	-- ========== 加班相关参数 ==========
	@加班人员 nvarchar(500) = NULL,              -- 普通加班人员（逗号分隔）
	@特殊加班人员 nvarchar(500) = NULL,          -- 特殊加班人员（逗号分隔）
	@是否加班 bit = 0,                           -- 是否加班（1=是，0=否）
	@是否休息日 bit = 0,                         -- 是否休息日（1=是，0=否）
	@是否法定休息日 bit = 0,                     -- 是否法定休息日（1=是，0=否）
	@用户选择班次 nvarchar(50) = NULL,           -- 用户选择的班次名称
	@班次标准工时 int = 8                        -- 班次标准工时（分钟），默认8小时
AS 
BEGIN
	SET NOCOUNT ON;
	
	declare @操作时间 datetime = getdate();
	declare @词条名称 nvarchar(50) = '辅助结束'
	declare @数据类别 nvarchar(50) = '生产操作'
	declare @词条ID int = -1
	declare @完成数量_New int = -1
	declare @任务状态 int = -1  --0待执行，1可执行，2已开工，4已完成。
	
	-- 加班计算相关变量
	declare @报工开始时间 datetime = NULL        -- 本次报工周期的开始时间
	declare @加班时长秒 int = 0                  -- 加班时长（秒）
	declare @加班开始时间 datetime = NULL
	declare @工作时间分钟 int = 0
	declare @总时长秒 int = 0
	declare @打卡开始秒 int
	declare @打卡结束秒 int
	
	-- 班次相关变量
	declare @当前班次 nvarchar(50)
	declare @班次开始时间 time
	declare @班次结束时间 time
	declare @班次开始秒 int
	declare @班次结束秒 int
	
	declare @OPCode nvarchar(50) = ''
	declare @OPName nvarchar(50) = ''
	declare @HTCode nvarchar(50) = ''
	declare @OrderNo int
	declare @工序名称 nvarchar(100)
	declare @物料编号 nvarchar(100)
	declare @物料描述 nvarchar(200)
	
	select @词条ID = 词条编号 from YL_基础表_数据字典 where 词条名称 = @词条名称 and 数据类别 = @数据类别
	
	Select @完成数量_New = isnull(完成数量,0) + @partCount,
	       @OPCode = [指派对象编号],
	       @OPName = 指派对象,
	       @HTCode = 合同号,
	       @OrderNo = 订单编号,
	       @工序名称 = 工序名称,
	       @物料编号 = 物料编号,
	       @物料描述 = 物料描述
	FROM View_生产订单_MES where TaskAID = @TaskAID
	
	select @任务状态 = isnull(任务状态,0) from View_生产订单_MES where TaskAID = @TaskAID
	
	-- ========== 获取报工开始时间（辅助开始时间） ==========
	SELECT TOP 1 @报工开始时间 = 开始时间
	FROM [YL_加工中心_操作记录表]
	WHERE TaskAID = @TaskAID 
	  AND 操作类别 = '辅助开始'
	  AND 开始时间 IS NOT NULL
	  AND ISNULL([已报工], 0) = 0
	ORDER BY 开始时间 DESC
	
	IF @报工开始时间 IS NULL
	BEGIN
		SELECT TOP 1 @报工开始时间 = 开始时间
		FROM [YL_加工中心_操作记录表]
		WHERE TaskAID = @TaskAID 
		  AND 操作类别 = '辅助开始'
		  AND 开始时间 IS NOT NULL
		ORDER BY 开始时间 DESC
	END
	
	IF @报工开始时间 IS NULL
	BEGIN
		SET @报工开始时间 = DATEADD(HOUR, -1, @操作时间)
	END
	
	-- ========== 获取打卡时间秒数 ==========
	SET @打卡开始秒 = DATEDIFF(SECOND, '00:00:00', CAST(@报工开始时间 AS time))
	SET @打卡结束秒 = DATEDIFF(SECOND, '00:00:00', CAST(@操作时间 AS time))
	SET @总时长秒 = @打卡结束秒 - @打卡开始秒
	
	-- ========== 确定当前班次 ==========
	
	-- ========== 确定当前班次 ==========
		SET @当前班次 = ISNULL(@用户选择班次, '')

		IF @当前班次 = ''
		BEGIN
			DECLARE @开始小时 int = DATEPART(HOUR, @报工开始时间)
			DECLARE @开始分钟 int = DATEPART(MINUTE, @报工开始时间)
			DECLARE @开始总分钟 int = @开始小时 * 60 + @开始分钟
    
			-- 白班：07:45 - 16:30
			-- 白班开始时间 07:45 = 465分钟
			-- 白班结束时间 16:30 = 990分钟
    
			IF @开始总分钟 >= 465 AND @开始总分钟 < 990
			BEGIN
				SET @当前班次 = '白班'
			END
			ELSE
			BEGIN
				SET @当前班次 = '夜班'
			END
		END

		-- ========== 计算加班时长 ==========
		IF @是否加班 = 1
		BEGIN
			-- 获取班次配置
			SELECT @班次开始时间 = 开始时间, @班次结束时间 = 结束时间
			FROM [班次表]
			WHERE 班次名称 = @当前班次
    
			-- 如果是休息日或法定休息日，整个时间段算加班
			IF (@是否休息日 = 1 OR @是否法定休息日 = 1)
			BEGIN
				SET @加班时长秒 = @总时长秒
				SET @加班开始时间 = @报工开始时间
			END
			ELSE
			BEGIN
				-- 工作日：根据班次类型拆分
				DECLARE @基准日期 date = CAST(@报工开始时间 AS DATE)
				DECLARE @班次结束时间_完整 datetime
        
				IF @当前班次 = '白班'
				BEGIN
					-- 白班：加班时间是超过班次结束时间之后的部分
					SET @班次结束时间_完整 = CAST(@基准日期 AS DATETIME) + CAST(@班次结束时间 AS datetime)
            
					IF @操作时间 > @班次结束时间_完整
					BEGIN
						SET @加班时长秒 = DATEDIFF(SECOND, @班次结束时间_完整, @操作时间)
						SET @加班开始时间 = @班次结束时间_完整
					END
				END
				ELSE  -- 夜班
				BEGIN
					DECLARE @班次开始时间_时分 time
					DECLARE @班次结束时间_时分 time
					DECLARE @班次开始分钟 int
					DECLARE @班次结束分钟 int
					DECLARE @打卡开始总分钟 int = DATEPART(HOUR, @报工开始时间) * 60 + DATEPART(MINUTE, @报工开始时间)
    
					SELECT @班次开始时间_时分 = 开始时间, @班次结束时间_时分 = 结束时间
					FROM [班次表]
					WHERE 班次名称 = @当前班次
    
					SET @班次开始分钟 = DATEPART(HOUR, @班次开始时间_时分) * 60 + DATEPART(MINUTE, @班次开始时间_时分)
					SET @班次结束分钟 = DATEPART(HOUR, @班次结束时间_时分) * 60 + DATEPART(MINUTE, @班次结束时间_时分)
    
					-- 判断打卡时间是否在夜班周期内
					-- 夜班周期：16:30 - 00:40（跨天）
					DECLARE @在班次内 bit = 0
    
					-- 晚上时段（16:30 - 23:59）
					IF @打卡开始总分钟 >= @班次开始分钟 AND @打卡开始总分钟 < 24*60
					BEGIN
						SET @在班次内 = 1
						SET @班次结束时间_完整 = DATEADD(DAY, 1, CAST(@基准日期 AS DATETIME) + CAST(@班次结束时间_时分 AS datetime))
					END
					-- 凌晨时段（00:00 - 00:40）
					ELSE IF @打卡开始总分钟 >= 0 AND @打卡开始总分钟 <= @班次结束分钟
					BEGIN
						SET @在班次内 = 1
						SET @班次结束时间_完整 = CAST(@基准日期 AS DATETIME) + CAST(@班次结束时间_时分 AS datetime)
					END
    
					IF @在班次内 = 1
					BEGIN
						-- 在班次内：加班时间 = 打卡结束时间 - 班次结束时间
						IF @操作时间 > @班次结束时间_完整
						BEGIN
							SET @加班时长秒 = DATEDIFF(SECOND, @班次结束时间_完整, @操作时间)
							SET @加班开始时间 = @班次结束时间_完整
						END
					END
					ELSE
					BEGIN
						-- 完全在班次外（如白天 08:00-17:00）：整个时间段算加班
						SET @加班时长秒 = @总时长秒
						SET @加班开始时间 = @报工开始时间
					END
				END
			END
    
			IF @加班时长秒 < 0 SET @加班时长秒 = 0
		END
	
	print '加班时长秒: ' + CAST(@加班时长秒 AS nvarchar)
	print '是否加班: ' + CAST(@是否加班 AS nvarchar)
	
	if(@指派数量 >= @完成数量_New)
	begin
		-- 更新加工状态、辅助完工数量
		Update MES_接口_生产计划_生产任务 
		set 加工状态 = @词条ID,
		    完成数量 = isnull(完成数量,0) + @partCount,
		    进度 = @完成数量_New / @指派数量 * 100 
		where AID = @TaskAID
		
		if(@指派数量 = @完成数量_New)
		begin
			Update MES_接口_生产计划_生产任务 set 任务状态 = 4 where AID = @TaskAID
		end
		
		-- ========== 生成操作记录（带加班参数） ==========
		EXEC [dbo].[MES_ProductCenter_OptRecord_Save]
			@dicItemName = @词条名称,
			@dataType = @数据类别,
			@TaskAID = @TaskAID,
			@optCount = @partCount,
			@optor = @optor,
			@optTime = @操作时间,
			@selectedOperators = @selectedOperators,
			@是否休息日 = @是否休息日,
			@是否法定休息日 = @是否法定休息日
		
		-- ========== 生成加班记录 ==========
		-- 如果有加班人员且加班时长>0且加班=是，保存加班记录
		IF (@加班人员 IS NOT NULL AND @加班人员 != '') AND @加班时长秒 > 0 AND @是否加班 = 1
		BEGIN
			-- 创建临时表存储所有加班人员及类型
			CREATE TABLE #TempPersons (
				人员名称 nvarchar(50),
				是否特殊 bit DEFAULT 0
			)
			
			-- 解析普通加班人员
			DECLARE @当前人员 nvarchar(50)
			DECLARE @位置 int
			DECLARE @人员列表 nvarchar(500) = @加班人员
			
			WHILE LEN(@人员列表) > 0
			BEGIN
				SET @位置 = CHARINDEX(',', @人员列表)
				
				IF @位置 > 0
				BEGIN
					SET @当前人员 = LTRIM(RTRIM(SUBSTRING(@人员列表, 1, @位置 - 1)))
					SET @人员列表 = SUBSTRING(@人员列表, @位置 + 1, LEN(@人员列表))
				END
				ELSE
				BEGIN
					SET @当前人员 = LTRIM(RTRIM(@人员列表))
					SET @人员列表 = ''
				END
				
				IF LEN(@当前人员) > 0 AND NOT EXISTS (SELECT 1 FROM #TempPersons WHERE 人员名称 = @当前人员)
				BEGIN
					INSERT INTO #TempPersons (人员名称, 是否特殊) VALUES (@当前人员, 0)
				END
			END
			
			-- 解析特殊加班人员
			IF (@特殊加班人员 IS NOT NULL AND @特殊加班人员 != '')
			BEGIN
				SET @人员列表 = @特殊加班人员
				WHILE LEN(@人员列表) > 0
				BEGIN
					SET @位置 = CHARINDEX(',', @人员列表)
					
					IF @位置 > 0
					BEGIN
						SET @当前人员 = LTRIM(RTRIM(SUBSTRING(@人员列表, 1, @位置 - 1)))
						SET @人员列表 = SUBSTRING(@人员列表, @位置 + 1, LEN(@人员列表))
					END
					ELSE
					BEGIN
						SET @当前人员 = LTRIM(RTRIM(@人员列表))
						SET @人员列表 = ''
					END
					
					IF LEN(@当前人员) > 0
					BEGIN
						IF EXISTS (SELECT 1 FROM #TempPersons WHERE 人员名称 = @当前人员)
						BEGIN
							UPDATE #TempPersons SET 是否特殊 = 1 WHERE 人员名称 = @当前人员
						END
						ELSE
						BEGIN
							INSERT INTO #TempPersons (人员名称, 是否特殊) VALUES (@当前人员, 1)
						END
					END
				END
			END
			
			-- 根据加班类型确定词条编号和名称
			DECLARE @加班词条编号 int
			DECLARE @加班词条名称 nvarchar(50)
			
			IF (@是否法定休息日 = 1)
			BEGIN
				IF (@是否加班 = 1)
				BEGIN
					SET @加班词条编号 = 11
					SET @加班词条名称 = '法定休息日加班'
				END
				ELSE
				BEGIN
					SET @加班词条编号 = 13
					SET @加班词条名称 = '法定休息日工作'
				END
			END
			ELSE IF (@是否休息日 = 1)
			BEGIN
				IF (@是否加班 = 1)
				BEGIN
					SET @加班词条编号 = 10
					SET @加班词条名称 = '休息日加班'
				END
				ELSE
				BEGIN
					SET @加班词条编号 = 12
					SET @加班词条名称 = '休息日工作'
				END
			END
			ELSE
			BEGIN
				SET @加班词条编号 = 8
				SET @加班词条名称 = '加班'
			END
			
			-- 获取工位名称
			DECLARE @工位名称 nvarchar(500)
			SELECT TOP 1 @工位名称 = 指派对象 FROM View_生产订单_MES WHERE TaskAID = @TaskAID
			
			DECLARE @工时秒 int = @加班时长秒
			DECLARE @加班开始时间_实际 datetime = ISNULL(@加班开始时间, @操作时间)
			DECLARE @加班时长分钟显示 int = CEILING(@加班时长秒 / 60.0)
			
			-- 插入加班记录
			INSERT INTO [dbo].[YL_加工中心_操作记录表] (
				操作类别编号, 
				操作类别, 
				阶段标识, 
				工序名称, 
				工位编号, 
				操作人, 
				合同号, 
				订单编号, 
				物料编号, 
				物料描述, 
				操作数值, 
				操作内容,
				操作描述, 
				开始时间, 
				结束时间, 
				总时长, 
				报工日期, 
				已报工, 
				不装配,
				最后编辑人, 
				最后编辑时间, 
				TaskAID, 
				工位名称,
				班次标准工时
			)
			SELECT 
				@加班词条编号,
				@加班词条名称,
				0,
				@工序名称,
				@OPCode,
				t.人员名称,
				'',
				@OrderNo,
				@物料编号,
				@物料描述,
				0,
				'辅助结束',
				CASE 
					WHEN @是否法定休息日 = 1 AND @是否加班 = 1 THEN '法定休息日辅助结束加班'
					WHEN @是否法定休息日 = 1 AND @是否加班 = 0 THEN '法定休息日辅助结束'
					WHEN @是否休息日 = 1 AND @是否加班 = 1 THEN '休息日辅助结束加班'
					WHEN @是否休息日 = 1 AND @是否加班 = 0 THEN '休息日辅助结束'
					ELSE '辅助结束加班（班次：' + ISNULL(@用户选择班次, @当前班次) + '）'
				END + 
				'，打卡时间：' + CONVERT(nvarchar(8), @报工开始时间, 108) + '-' + CONVERT(nvarchar(8), @操作时间, 108) +
				'，加班时长：' + CAST(@加班时长分钟显示 AS nvarchar) + '分钟（' + CAST(@加班时长秒 AS nvarchar) + '秒）' +
				'，辅助工件数量：' + CAST(@partCount AS nvarchar) +
				CASE 
					WHEN t.是否特殊 = 1 THEN '，特殊加班人员'
					ELSE ''
				END,
				@加班开始时间_实际,
				@操作时间,
				@工时秒,
				CONVERT(date, @操作时间),
				1,
				'否',
				@optor,
				GETDATE(),
				@TaskAID,
				@工位名称,
				CASE 
					WHEN t.是否特殊 = 1 THEN @班次标准工时 
					ELSE 8 
				END
			FROM #TempPersons t
			
			-- 清理临时表
			DROP TABLE #TempPersons
		END
		
		select 1 as result
	end
	if(@指派数量 < @完成数量_New)
		select 0 as result
END
GO
/****** Object:  StoredProcedure [dbo].[MES_ProductTask_HelpStart]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[MES_ProductTask_HelpStart]
	@TaskAID bigint,
	@optor nvarchar(50)
AS 
BEGIN
	declare @操作时间 datetime=getdate();
	declare @词条名称 nvarchar(50)='辅助开始'
	declare @数据类别 nvarchar(50)='生产操作'
	declare @词条ID int=-1
	declare @任务状态 int=-1  --0待执行，1可执行，2已开工，4已完成。
	select @词条ID=词条编号 from YL_基础表_数据字典 where 词条名称=@词条名称 and 数据类别=@数据类别
	select @任务状态=isnull(任务状态,0)from View_生产订单_MES where TaskAID=@TaskAID
	if(@任务状态 = 1) --可执行任务
		begin
			Update MES_接口_生产计划_生产任务 set 可执行=1,加工状态=@词条ID,开工时间=@操作时间,操作时间=@操作时间 where AID=@TaskAID
		end
	if(@任务状态 = 2) --可执行任务
		begin
			Update MES_接口_生产计划_生产任务 set 可执行=1,加工状态=@词条ID,开工时间=@操作时间,操作时间=@操作时间  where AID=@TaskAID
		end
	--生成操作记录
	EXEC [dbo].[MES_ProductCenter_OptRecord_Save]
		@dicItemName = @词条名称,
		@dataType = @数据类别,
		@TaskAID = @TaskAID,
		--@optCount = @checkResult,  --操作数值
		--@optDescription = @helfDescription,
		@optor = @optor,
		@optTime = @操作时间
END
GO
/****** Object:  StoredProcedure [dbo].[MES_ProductTask_MaterialRecieved]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[MES_ProductTask_MaterialRecieved]
	@TaskAID bigint,
	@recievCount int,
	@optor nvarchar(50)
AS
declare @操作时间 datetime=getdate()
declare @任务状态 int
BEGIN
	--更新收料数量、收料状态、可执行状态
	select @任务状态 = 任务状态 from MES_接口_生产计划_生产任务 where AID=@TaskAID
	if(@任务状态 <= 1 )
	begin 
		Update MES_接口_生产计划_生产任务 
		set 任务状态=case when isnull(收料数量,0)+@recievCount>0 then 1 else 0 end,   --当收料数量>0时，变为可执行
		收料=case when isnull(收料数量,0)+@recievCount>0 then 1 else 0 end,
		收料数量=isnull(收料数量,0)+@recievCount,
		修改时间=@操作时间
		where AID=@TaskAID
	end
	if(@任务状态 > 1 )
	begin 
		Update MES_接口_生产计划_生产任务 
		set 收料=case when isnull(收料数量,0)+@recievCount>0 then 1 else 0 end,
		收料数量=isnull(收料数量,0)+@recievCount,
		修改时间=@操作时间
		where AID=@TaskAID
	end
	--生成操作记录
	declare @词条名称 nvarchar(50)='收料'
	declare @数据类别 nvarchar(50)='生产操作'
	EXEC	[dbo].[MES_ProductCenter_OptRecord_Save]
		@dicItemName = @词条名称,
		@dataType = @数据类别,
		@TaskAID = @TaskAID,
		@optCount = @recievCount,
		--@optDescription = N'Description',
		@optor = @optor,
		@optTime = @操作时间


END
GO
/****** Object:  StoredProcedure [dbo].[MES_ProductTask_Notice]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[MES_ProductTask_Notice]
    @TaskAID BIGINT,
	@外协通知 int = NULL
AS

BEGIN
    UPDATE [MES_接口_生产计划_生产任务] set [外协通知] =  @外协通知  where [AID] = @TaskAID
END
GO
/****** Object:  StoredProcedure [dbo].[MES_ProductTask_ProdReport]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[MES_ProductTask_ProdReport]
	@TaskAID bigint,
	@BindRpt_ALLtaskids nvarchar(500),           -- 捆绑报工任务
	@rptDate nvarchar(50),                       -- 报工日期
	@rptShift nvarchar(50),                      -- 报工班次
	@partCount int,                              -- 报工数量
	@rptDesc nvarchar(50),                       -- 报工说明
	@optor nvarchar(50),                         -- 操作人
	@前序不合格总数 nvarchar(500),                -- 前序不合格总数（与TaskAID一一对应）
	-- ========== 加班相关参数 ==========
	@加班人员 nvarchar(500) = NULL,              -- 普通加班人员（逗号分隔）
	@特殊加班人员 nvarchar(500) = NULL,          -- 特殊加班人员（逗号分隔）
	@是否加班 nvarchar(10) = '0',                -- 是否加班（'1'=是，'0'=否）
	@是否休息日 nvarchar(10) = '0',              -- 是否休息日（'1'=是，'0'=否）
	@是否法定休息日 nvarchar(10) = '0',          -- 是否法定休息日（'1'=是，'0'=否）
	@用户选择班次 nvarchar(50) = NULL,           -- 用户选择的班次名称
	@班次标准工时 int = 8                        -- 班次标准工时（分钟），默认8小时
AS 
BEGIN
	SET NOCOUNT ON;
	
	-- ========== 参数类型转换（字符串转bit） ==========
	DECLARE @是否加班_bit bit = CASE 
		WHEN @是否加班 = '1' OR @是否加班 = 'true' OR @是否加班 = 'True' OR @是否加班 = 'TRUE' THEN 1 
		ELSE 0 
	END
	
	DECLARE @是否休息日_bit bit = CASE 
		WHEN @是否休息日 = '1' OR @是否休息日 = 'true' OR @是否休息日 = 'True' OR @是否休息日 = 'TRUE' THEN 1 
		ELSE 0 
	END
	
	DECLARE @是否法定休息日_bit bit = CASE 
		WHEN @是否法定休息日 = '1' OR @是否法定休息日 = 'true' OR @是否法定休息日 = 'True' OR @是否法定休息日 = 'TRUE' THEN 1 
		ELSE 0 
	END
	
	-- ========== 变量声明 ==========
	declare @指派数量 decimal(16,2) = -1
	declare @收料数量 int = -1
	declare @完成数量_New int = -1
	declare @操作时间 datetime = getdate()
	declare @词条名称 nvarchar(50) = '报工'
	declare @数据类别 nvarchar(50) = '生产操作'
	declare @词条ID int = -1
	declare @OPCode nvarchar(50) = ''
	declare @OPName nvarchar(50) = ''
	declare @HTCode nvarchar(50) = ''
	declare @OrderNo int
	declare @最新不合格数 int
	
	-- 加班计算相关变量（使用秒）
	declare @报工开始时间 datetime = NULL        -- 本次报工周期的开始时间
	declare @加班时长秒 int = 0                  -- 加班时长（秒）
	declare @加班开始时间 datetime = NULL
	declare @工作时间分钟 int = 0
	declare @报工日期 date = CAST(@rptDate AS DATE)
	declare @最小班次标准工时 int = 8
	
	-- 班次相关变量（使用秒）
	declare @当前班次 nvarchar(50)
	declare @对班 nvarchar(50)
	declare @班次开始时间 time
	declare @班次结束时间 time
	declare @打卡开始秒 int
	declare @打卡结束秒 int
	declare @中点秒 int
	declare @总时长秒 int
	
	-- 创建临时表存储所有加班人员及类型
	CREATE TABLE #TempPersons (
		人员名称 nvarchar(50),
		是否特殊 bit DEFAULT 0
	)
	
	-- ========== 获取报工词条编号 ==========
	select @词条ID = 词条编号 
	from YL_基础表_数据字典 
	where 词条名称 = @词条名称 and 数据类别 = @数据类别
	
	-- ========== 获取主任务信息 ==========
	Select 
		@指派数量 = 指派数量,
		@收料数量 = 收料数量,
		@完成数量_New = isnull(完成数量, 0) + @partCount,
		@OPCode = [指派对象编号],
		@OPName = 指派对象,
		@HTCode = 合同号,
		@OrderNo = 订单编号
	FROM View_生产订单_MES 
	where TaskAID = @TaskAID
	
	-- ========== 获取报工开始时间 ==========
	SELECT TOP 1 @报工开始时间 = 开始时间
	FROM [YL_加工中心_操作记录表]
	WHERE TaskAID = @TaskAID 
	  AND 操作类别 = '开始加工'
	  AND 开始时间 IS NOT NULL
	  AND ISNULL([已报工], 0) = 0
	ORDER BY 开始时间 DESC
	
	IF @报工开始时间 IS NULL
	BEGIN
		SELECT TOP 1 @报工开始时间 = 开始时间
		FROM [YL_加工中心_操作记录表]
		WHERE TaskAID = @TaskAID 
		  AND 操作类别 = '开始加工'
		  AND 开始时间 IS NOT NULL
		ORDER BY 开始时间 DESC
	END
	
	--IF @报工开始时间 IS NULL
	--BEGIN
	--	SET @报工开始时间 = DATEADD(HOUR, -1, @rptDate)
	--END
	
	-- ========== 获取打卡时间秒数 ==========
	SET @打卡开始秒 = DATEDIFF(SECOND, '00:00:00', CAST(@报工开始时间 AS time))
	SET @打卡结束秒 = DATEDIFF(SECOND, '00:00:00', CAST(@rptDate AS time))
	-- 修复：跨天处理
	IF @打卡结束秒 < @打卡开始秒
		SET @打卡结束秒 = @打卡结束秒 + 24 * 3600
	SET @总时长秒 = @打卡结束秒 - @打卡开始秒
	SET @中点秒 = @打卡开始秒 + (@总时长秒 / 2)
	
	-- ========== 获取班次标准工时最小值 ==========
	SELECT @最小班次标准工时 = MIN(班次标准工时 / 60)
	FROM [YL_加工中心_操作记录表]
	WHERE TaskAID = @TaskAID 
	  AND 操作类别 IN ('加班', '休息日加班', '法定休息日加班', '休息日工作', '法定休息日工作')
	  AND CAST(开始时间 AS DATE) = @报工日期
	  AND 班次标准工时 > 0
	
	IF @最小班次标准工时 IS NULL OR @最小班次标准工时 = 0
		SET @最小班次标准工时 = @班次标准工时
	ELSE
		IF @班次标准工时 < @最小班次标准工时
			SET @最小班次标准工时 = @班次标准工时
	
	-- ========== 解析加班人员 ==========
	-- 解析普通加班人员
	IF (@加班人员 IS NOT NULL AND @加班人员 != '')
	BEGIN
		DECLARE @当前人员 nvarchar(50)
		DECLARE @位置 int
		DECLARE @人员列表 nvarchar(500) = @加班人员
		
		WHILE LEN(@人员列表) > 0
		BEGIN
			SET @位置 = CHARINDEX(',', @人员列表)
			
			IF @位置 > 0
			BEGIN
				SET @当前人员 = LTRIM(RTRIM(SUBSTRING(@人员列表, 1, @位置 - 1)))
				SET @人员列表 = SUBSTRING(@人员列表, @位置 + 1, LEN(@人员列表))
			END
			ELSE
			BEGIN
				SET @当前人员 = LTRIM(RTRIM(@人员列表))
				SET @人员列表 = ''
			END
			
			IF LEN(@当前人员) > 0 AND NOT EXISTS (SELECT 1 FROM #TempPersons WHERE 人员名称 = @当前人员)
			BEGIN
				INSERT INTO #TempPersons (人员名称, 是否特殊) VALUES (@当前人员, 0)
			END
		END
	END
	
	-- 解析特殊加班人员
	IF (@特殊加班人员 IS NOT NULL AND @特殊加班人员 != '')
	BEGIN
		SET @人员列表 = @特殊加班人员
		WHILE LEN(@人员列表) > 0
		BEGIN
			SET @位置 = CHARINDEX(',', @人员列表)
			
			IF @位置 > 0
			BEGIN
				SET @当前人员 = LTRIM(RTRIM(SUBSTRING(@人员列表, 1, @位置 - 1)))
				SET @人员列表 = SUBSTRING(@人员列表, @位置 + 1, LEN(@人员列表))
			END
			ELSE
			BEGIN
				SET @当前人员 = LTRIM(RTRIM(@人员列表))
				SET @人员列表 = ''
			END
			
			IF LEN(@当前人员) > 0
			BEGIN
				IF EXISTS (SELECT 1 FROM #TempPersons WHERE 人员名称 = @当前人员)
				BEGIN
					UPDATE #TempPersons SET 是否特殊 = 1 WHERE 人员名称 = @当前人员
				END
				ELSE
				BEGIN
					INSERT INTO #TempPersons (人员名称, 是否特殊) VALUES (@当前人员, 1)
				END
			END
		END
	END
	
	-- ========== 确定当前班次和对班 ==========
	SET @当前班次 = ISNULL(@用户选择班次, @rptShift)
	
	IF @当前班次 LIKE '%白%' OR @当前班次 = '白班'
		SET @对班 = '夜班'
	ELSE
		SET @对班 = '白班'
	
	-- ========== 创建临时表存储需要处理的班次 ==========
	CREATE TABLE #班次处理 (
		班次名称 nvarchar(50),
		是否操作人班次 bit,
		工作时间分钟 int DEFAULT 0,
		加班时长秒 int DEFAULT 0,
		加班开始时间 datetime NULL
	)
	
	INSERT INTO #班次处理 (班次名称, 是否操作人班次) VALUES (@当前班次, 1)
	INSERT INTO #班次处理 (班次名称, 是否操作人班次) VALUES (@对班, 0)
	
	-- ========== 循环处理每个班次 ==========
	DECLARE @当前处理班次 nvarchar(50)
	DECLARE @是否操作人班次 bit
	DECLARE @班次开始秒 int
	DECLARE @班次结束秒 int
	DECLARE @重叠开始秒 int
	DECLARE @重叠结束秒 int
	DECLARE @重叠时长秒 int

	DECLARE 班次游标 CURSOR FOR SELECT 班次名称, 是否操作人班次 FROM #班次处理
	OPEN 班次游标
	FETCH NEXT FROM 班次游标 INTO @当前处理班次, @是否操作人班次

	WHILE @@FETCH_STATUS = 0
	BEGIN
		-- 获取该班次的开始和结束时间
		SELECT @班次开始时间 = 开始时间, @班次结束时间 = 结束时间
		FROM [班次表]
		WHERE 班次名称 = @当前处理班次
	
		SET @班次开始秒 = DATEPART(HOUR, @班次开始时间) * 3600 + DATEPART(MINUTE, @班次开始时间) * 60 + DATEPART(SECOND, @班次开始时间)
		SET @班次结束秒 = DATEPART(HOUR, @班次结束时间) * 3600 + DATEPART(MINUTE, @班次结束时间) * 60 + DATEPART(SECOND, @班次结束时间)
	
		-- 处理跨天班次
		IF @班次结束秒 < @班次开始秒
			SET @班次结束秒 = @班次结束秒 + 24 * 3600
	
		-- 计算与打卡时间的重叠部分
		SET @重叠开始秒 = CASE WHEN @打卡开始秒 > @班次开始秒 THEN @打卡开始秒 ELSE @班次开始秒 END
		SET @重叠结束秒 = CASE WHEN @打卡结束秒 < @班次结束秒 THEN @打卡结束秒 ELSE @班次结束秒 END
	
		-- ⭐ 修改：完全不重叠时，整个打卡时间算加班
		IF @重叠结束秒 > @重叠开始秒
		BEGIN
			-- 有重叠，按重叠部分计算
			SET @重叠时长秒 = @重叠结束秒 - @重叠开始秒
		END
		ELSE
		BEGIN
			-- 完全不重叠：整个打卡时间算加班
			SET @重叠时长秒 = @总时长秒
			-- 如果是操作人班次，加班开始时间设为报工开始时间
			IF @是否操作人班次 = 1
			BEGIN
				SET @加班开始时间 = @报工开始时间
			END
		END
	
		IF @是否操作人班次 = 1
		BEGIN
			-- ========== 操作人班次：按规则拆分 ==========
			-- 使用转换后的变量 @是否休息日_bit 和 @是否法定休息日_bit
			print @是否休息日_bit
			print @重叠时长秒
			print @总时长秒
			IF (@是否休息日_bit = 1 OR @是否法定休息日_bit = 1)
			BEGIN
				-- 休息日/法定节假日：加班时长计算
				DECLARE @超出部分秒 int = 0
				DECLARE @压缩系数 float = CAST(@最小班次标准工时 AS float) / 8.0
				DECLARE @重叠加班秒 int = 0
    
				-- 超出部分 = 总时长 - 重叠时长
				SET @超出部分秒 = @总时长秒 - @重叠时长秒
    
				-- 重叠部分的加班时长（按压缩系数折算）
				SET @重叠加班秒 = ROUND(@重叠时长秒 * @压缩系数, 0)
    
				-- 总加班时长
				SET @加班时长秒 = @重叠加班秒 + @超出部分秒
				print @重叠加班秒
				print @超出部分秒
				print @加班时长秒
				-- 防止负数
				IF @加班时长秒 < 0 SET @加班时长秒 = 0
    
				-- 工作时间设为0
				SET @工作时间分钟 = 0
    
				-- 加班开始时间
				IF @加班开始时间 IS NULL
					SET @加班开始时间 = @报工开始时间
			END
			ELSE
			BEGIN
				-- 工作日：根据班次类型拆分
				IF @当前处理班次 LIKE '%白%' OR @当前处理班次 = '白班'
				BEGIN
					-- 白班：班次结束时间之前的为工作时间，之后的为加班时间
					-- 获取班次结束时间
					DECLARE @班次结束时间_完整 datetime = CAST(CAST(@rptDate AS DATE) AS DATETIME) + CAST(@班次结束时间 AS DATETIME)
        
					-- 情况1：开始时间已经晚于班次结束时间（全部算加班）
					IF @报工开始时间 >= @班次结束时间_完整
					BEGIN
						SET @工作时间分钟 = 0
						SET @加班时长秒 = @总时长秒
						SET @加班开始时间 = @报工开始时间
					END
					-- 情况2：正常情况，开始时间在班次结束时间之前
					ELSE IF @rptDate > @班次结束时间_完整
					BEGIN
						-- 工作时间 = 班次结束时间 - 打卡开始时间
						SET @工作时间分钟 = DATEDIFF(SECOND, @报工开始时间, @班次结束时间_完整) / 60.0
						-- 加班时间 = 打卡结束时间 - 班次结束时间
						SET @加班时长秒 = DATEDIFF(SECOND, @班次结束时间_完整, @rptDate)
						SET @加班开始时间 = @班次结束时间_完整
					END
					ELSE
					BEGIN
						-- 全部算工作时间，没有加班
						SET @工作时间分钟 = @总时长秒 / 60.0
						SET @加班时长秒 = 0
						SET @加班开始时间 = NULL
					END
				END
				ELSE  -- 夜班逻辑
				BEGIN
					-- 夜班：班次时间范围内为工作时间，范围外为加班时间
					-- 获取完整的班次开始和结束时间
					DECLARE @班次开始时间_完整 datetime
					DECLARE @班次结束时间_完整2 datetime
    
					-- 判断开始时间属于哪个夜班周期
					IF DATEPART(HOUR, @报工开始时间) >= DATEPART(HOUR, @班次开始时间)
					BEGIN
						-- 晚上时段（16:30-23:59）：开始时间是当天，结束时间是次日
						SET @班次开始时间_完整 = DATEADD(SECOND, @班次开始秒, CAST(CAST(@报工开始时间 AS DATE) AS DATETIME))
						SET @班次结束时间_完整2 = DATEADD(SECOND, @班次结束秒, CAST(CAST(@报工开始时间 AS DATE) AS DATETIME))
					END
					ELSE
					BEGIN
						-- 凌晨时段（00:00-00:40）：开始时间是前一天，结束时间是当天
						SET @班次开始时间_完整 = DATEADD(SECOND, @班次开始秒, DATEADD(DAY, -1, CAST(CAST(@报工开始时间 AS DATE) AS DATETIME)))
						SET @班次结束时间_完整2 = DATEADD(SECOND, @班次结束秒, CAST(CAST(@报工开始时间 AS DATE) AS DATETIME))
					END
    
					-- 计算工作结束时间（取打卡结束和班次结束中较早者）
					DECLARE @工作结束时间 datetime = CASE 
						WHEN @rptDate < @班次结束时间_完整2 THEN @rptDate 
						ELSE @班次结束时间_完整2 
					END
    
					-- 只有打卡时间与班次有重叠时才计算工作时间
					IF @报工开始时间 < @班次结束时间_完整2 AND @rptDate > @班次开始时间_完整
					BEGIN
						DECLARE @工作开始时间 datetime = CASE 
							WHEN @报工开始时间 > @班次开始时间_完整 THEN @报工开始时间 
							ELSE @班次开始时间_完整 
						END
        
						SET @工作时间分钟 = DATEDIFF(SECOND, @工作开始时间, @工作结束时间) / 60.0
        
						-- 只有打卡结束时间超过班次结束时间才有加班
						IF @rptDate > @班次结束时间_完整2
						BEGIN
							SET @加班时长秒 = DATEDIFF(SECOND, @班次结束时间_完整2, @rptDate)
							-- 防止负数
							IF @加班时长秒 < 0 SET @加班时长秒 = 0
							SET @加班开始时间 = @班次结束时间_完整2
						END
						ELSE
						BEGIN
							SET @加班时长秒 = 0
							SET @加班开始时间 = NULL
						END
					END
					ELSE
					BEGIN
						-- 完全不重叠，全部算加班
						SET @工作时间分钟 = 0
						SET @加班时长秒 = @总时长秒
						SET @加班开始时间 = @报工开始时间
					END
				END
			END
		
			-- 更新临时表
			print @工作时间分钟
			print @加班时长秒
			print @加班开始时间
			UPDATE #班次处理 
			SET 工作时间分钟 = @工作时间分钟,
				加班时长秒 = @加班时长秒,
				加班开始时间 = @加班开始时间
			WHERE 班次名称 = @当前处理班次
		END
		ELSE
		BEGIN
			-- ========== 对班：只记录重叠部分为工作时间 ==========
			UPDATE #班次处理 
			SET 工作时间分钟 = @重叠时长秒 / 60.0
			WHERE 班次名称 = @当前处理班次
		END
	
		-- 重置加班开始时间变量
		SET @加班开始时间 = NULL
	
		FETCH NEXT FROM 班次游标 INTO @当前处理班次, @是否操作人班次
	END

	CLOSE 班次游标
	DEALLOCATE 班次游标
	
	-- ========== 生成工作时间记录（调用 OptRecord_Save） ==========
	-- 创建临时表存储所有TaskAID和对应的前序不合格数
	CREATE TABLE #TaskData (TaskAID bigint, 前序不合格数 int)
	
	-- 解析TaskAID和前序不合格数
	IF @BindRpt_ALLtaskids <> '' AND @前序不合格总数 <> ''
	BEGIN
		CREATE TABLE #TaskIDs (ID int identity(1,1), TaskAID bigint)
		CREATE TABLE #DefectCounts (ID int identity(1,1), 前序不合格数 int)
		
		INSERT INTO #TaskIDs (TaskAID)
		SELECT value FROM STRING_SPLIT(@BindRpt_ALLtaskids, ',')
		
		INSERT INTO #DefectCounts (前序不合格数)
		SELECT value FROM STRING_SPLIT(@前序不合格总数, ',')
		
		INSERT INTO #TaskData (TaskAID, 前序不合格数)
		SELECT t.TaskAID, d.前序不合格数
		FROM #TaskIDs t
		INNER JOIN #DefectCounts d ON t.ID = d.ID
		
		DROP TABLE #TaskIDs
		DROP TABLE #DefectCounts
	END
	
	IF NOT EXISTS (SELECT 1 FROM #TaskData WHERE TaskAID = @TaskAID)
	BEGIN
		INSERT INTO #TaskData (TaskAID, 前序不合格数)
		VALUES (@TaskAID, 0)
	END
	
	SELECT @最新不合格数 = 前序不合格数 FROM #TaskData WHERE TaskAID = @TaskAID
	
	-- 验证并执行报工
	IF (@完成数量_New + @最新不合格数 <= @指派数量)
	BEGIN
		-- 为所有TaskAID生成报工操作记录
		DECLARE @CurrentTaskAID bigint
		DECLARE @CurrentDefectCount int
		DECLARE task_cursor CURSOR FOR SELECT TaskAID, 前序不合格数 FROM #TaskData
		
		OPEN task_cursor
		FETCH NEXT FROM task_cursor INTO @CurrentTaskAID, @CurrentDefectCount
		
		WHILE @@FETCH_STATUS = 0
		BEGIN
			IF @CurrentTaskAID > 0
			BEGIN
				EXEC [dbo].[MES_ProductCenter_OptRecord_Save]
					@dicItemName = @词条名称,
					@dataType = @数据类别,
					@TaskAID = @CurrentTaskAID,
					@optCount = @partCount,
					@optDescription = @rptDesc,
					@optor = @optor,
					@optTime = @操作时间,
					@selectedOperators = NULL,
					@是否休息日 = @是否休息日_bit,
					@是否法定休息日 = @是否法定休息日_bit
			END
			
			FETCH NEXT FROM task_cursor INTO @CurrentTaskAID, @CurrentDefectCount
		END
		
		CLOSE task_cursor
		DEALLOCATE task_cursor
		
		-- 更新任务状态
		IF (@完成数量_New + @最新不合格数 < @指派数量)
		BEGIN
			UPDATE MES_接口_生产计划_生产任务 
			SET 加工状态 = @词条ID, 
				完成数量 = ISNULL(完成数量, 0) + @partCount, 
				进度 = (ISNULL(完成数量, 0) + @partCount + ISNULL(td.前序不合格数, 0)) / 指派数量 * 100 
			FROM MES_接口_生产计划_生产任务 t
			INNER JOIN #TaskData td ON t.AID = td.TaskAID
		END
		ELSE IF (@完成数量_New + @最新不合格数 = @指派数量)
		BEGIN
			UPDATE MES_接口_生产计划_生产任务 
			SET 加工状态 = @词条ID, 
				完成数量 = ISNULL(完成数量, 0) + @partCount,
				任务状态 = 4, 
				进度 = (ISNULL(完成数量, 0) + @partCount + ISNULL(td.前序不合格数, 0)) / 指派数量 * 100 
			FROM MES_接口_生产计划_生产任务 t
			INNER JOIN #TaskData td ON t.AID = td.TaskAID
		END
		
		-- 计算报工工时
		declare @生产工时_秒 int = 0
		declare @辅助工时_秒 int = 0
		
		SELECT @生产工时_秒 = SUM([实际工时]) 
		FROM [YL_加工中心_操作记录表]
		WHERE 工位编号 = @OPCode 
		  AND 操作类别 = '开始加工' 
		  AND TaskAID IN (SELECT TaskAID FROM #TaskData)
		  AND ISNULL([已报工], 0) = 0 
		  AND 操作人 = @optor
		
		SELECT @辅助工时_秒 = SUM([实际工时]) 
		FROM [YL_加工中心_操作记录表]
		WHERE 工位编号 = @OPCode 
		  AND 操作类别 = '辅助开始' 
		  AND TaskAID IN (SELECT TaskAID FROM #TaskData)
		  AND ISNULL([已报工], 0) = 0 
		  AND 操作人 = @optor
		
		-- 保存报工记录
		DECLARE task_cursor2 CURSOR FOR SELECT TaskAID FROM #TaskData
		
		OPEN task_cursor2
		FETCH NEXT FROM task_cursor2 INTO @CurrentTaskAID
		
		WHILE @@FETCH_STATUS = 0
		BEGIN
			INSERT INTO [dbo].[YL_加工中心_报工记录]
				([报工日期], [班次], [工位编号], [工位名称], [操作人], [工时类型], 
				 [报工数量], [工时], [报工说明], [合同号], [订单编号], [TaskAID], 
				 [TaskAID_Binding], [报工时间])
			VALUES
				(@rptDate, @rptShift, @OPCode, @OPName, @optor, '辅助工时',
				 @partCount, @辅助工时_秒, @rptDesc, @HTCode, @OrderNo, @CurrentTaskAID,
				 @BindRpt_ALLtaskids, @操作时间)
			
			INSERT INTO [dbo].[YL_加工中心_报工记录]
				([报工日期], [班次], [工位编号], [工位名称], [操作人], [工时类型], 
				 [报工数量], [工时], [报工说明], [合同号], [订单编号], [TaskAID], 
				 [TaskAID_Binding], [报工时间])
			VALUES
				(@rptDate, @rptShift, @OPCode, @OPName, @optor, '生产工时',
				 @partCount, @生产工时_秒, @rptDesc, @HTCode, @OrderNo, @CurrentTaskAID,
				 @BindRpt_ALLtaskids, @操作时间)
			
			FETCH NEXT FROM task_cursor2 INTO @CurrentTaskAID
		END
		
		CLOSE task_cursor2
		DEALLOCATE task_cursor2
		
		-- 更新操作记录的报工状态
		UPDATE [YL_加工中心_操作记录表] 
		SET 已报工 = 1
		WHERE 工位编号 = @OPCode 
		  AND (操作类别 = '辅助开始' OR 操作类别 = '开始加工') 
		  AND TaskAID IN (SELECT TaskAID FROM #TaskData)
		  AND ISNULL([已报工], 0) = 0 
		  AND 操作人 = @optor
		
		DROP TABLE #TaskData
		
		-- ========== 生成加班记录（只生成操作人班次） ==========
		-- 获取操作人班次的加班信息
		DECLARE @操作人班次加班秒 int = 0
		DECLARE @操作人班次加班开始时间 datetime = NULL
		DECLARE @操作人班次工作时间分钟 int = 0
		
		SELECT @操作人班次工作时间分钟 = 工作时间分钟,
			   @操作人班次加班秒 = 加班时长秒,
			   @操作人班次加班开始时间 = 加班开始时间
		FROM #班次处理
		WHERE 班次名称 = @当前班次
		

		-- 如果有加班人员且加班=是，保存加班记录（使用转换后的变量）
		IF EXISTS (SELECT 1 FROM #TempPersons) AND @是否加班_bit = 1
		BEGIN
			DECLARE @工时秒 int 
			DECLARE @加班开始时间_实际 datetime = @操作人班次加班开始时间
			DECLARE @工位名称 nvarchar(500)
			DECLARE @工序名称 nvarchar(100)
			DECLARE @物料编号 nvarchar(100)
			DECLARE @物料描述 nvarchar(200)
		
			
			-- 根据加班类型确定词条编号和名称
			DECLARE @加班词条编号 int
			DECLARE @加班词条名称 nvarchar(50)

			-- 使用实际的开始时间和结束时间（@操作时间）重新计算
			SET @工时秒 = DATEDIFF(SECOND, @加班开始时间_实际, @操作时间)
    
			-- 防止负数
			IF @工时秒 < 0 
				SET @工时秒 = 0
    
			-- 用于显示
			DECLARE @加班时长分钟显示 int = CEILING(@工时秒 / 60.0)
			
			-- 使用转换后的变量
			IF (@是否法定休息日_bit = 1)
			BEGIN
				IF (@是否加班_bit = 1)
				BEGIN
					SET @加班词条编号 = 11
					SET @加班词条名称 = '法定休息日加班'
				END
				ELSE
				BEGIN
					SET @加班词条编号 = 13
					SET @加班词条名称 = '法定休息日工作'
				END
			END
			ELSE IF (@是否休息日_bit = 1)
			BEGIN
				IF (@是否加班_bit = 1)
				BEGIN
					SET @加班词条编号 = 10
					SET @加班词条名称 = '休息日加班'
				END
				ELSE
				BEGIN
					SET @加班词条编号 = 12
					SET @加班词条名称 = '休息日工作'
				END
			END
			ELSE
			BEGIN
				SET @加班词条编号 = 8
				SET @加班词条名称 = '加班'
			END
			
			-- 获取工位信息和任务信息
			SELECT TOP 1 
				@工位名称 = 指派对象,
				@工序名称 = 工序名称,
				@物料编号 = 物料编号,
				@物料描述 = 物料描述
			FROM View_生产订单_MES 
			WHERE TaskAID = @TaskAID
			
			-- 插入加班记录（只有操作人班次）
			INSERT INTO [dbo].[YL_加工中心_操作记录表] (
				操作类别编号, 
				操作类别, 
				阶段标识, 
				工序名称, 
				工位编号, 
				操作人, 
				合同号, 
				订单编号, 
				物料编号, 
				物料描述, 
				操作数值, 
				操作内容,
				操作描述, 
				开始时间, 
				结束时间, 
				总时长, 
				报工日期, 
				已报工, 
				不装配,
				最后编辑人, 
				最后编辑时间, 
				TaskAID, 
				工位名称,
				班次标准工时
			)
			SELECT 
				@加班词条编号,
				@加班词条名称,
				0,
				@工序名称,
				@OPCode,
				t.人员名称,
				'',
				@OrderNo,
				@物料编号,
				@物料描述,
				0,
				'报工',
				CASE 
					WHEN @是否法定休息日_bit = 1 AND @是否加班_bit = 1 THEN '法定休息日报工加班'
					WHEN @是否法定休息日_bit = 1 AND @是否加班_bit = 0 THEN '法定休息日报工'
					WHEN @是否休息日_bit = 1 AND @是否加班_bit = 1 THEN '休息日报工加班'
					WHEN @是否休息日_bit = 1 AND @是否加班_bit = 0 THEN '休息日报工'
					ELSE '工作日加班（班次：' + @当前班次 + '）'
				END + 
				'，打卡时间：' + CONVERT(nvarchar(8), @报工开始时间, 108) + '-' + CONVERT(nvarchar(8), @rptDate, 108) +
				'，加班时长：' + CAST(@加班时长分钟显示 AS nvarchar) + '分钟（' + CAST(@操作人班次加班秒 AS nvarchar) + '秒）' +
				CASE 
					WHEN t.是否特殊 = 1 THEN '，班次标准工时：' + CAST(@最小班次标准工时 AS nvarchar) + '小时（最小值），特殊加班人员'
					ELSE '，班次标准工时：8小时'
				END,
				@加班开始时间_实际,
				@操作时间,
				@工时秒,
				CONVERT(date, @rptDate),
				1,
				'否',
				@optor,
				GETDATE(),
				@TaskAID,
				@工位名称,
				CASE 
					WHEN t.是否特殊 = 1 THEN @最小班次标准工时 
					ELSE 8 
				END
			FROM #TempPersons t
		END
		
		-- 清理临时表
		DROP TABLE #班次处理
		IF OBJECT_ID('tempdb..#TempPersons') IS NOT NULL
			DROP TABLE #TempPersons
		
		SELECT 0 as rptResult, '' as rptMsg
    END
	ELSE
	BEGIN
		DROP TABLE #TaskData
		DROP TABLE #班次处理
		IF OBJECT_ID('tempdb..#TempPersons') IS NOT NULL
			DROP TABLE #TempPersons
		SELECT -1 as rptResult, '报工数量与完成数量之和已超出收料数量或指派数量！' as rptMsg
	END
END
GO
/****** Object:  StoredProcedure [dbo].[MES_ProductTask_Rest]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[MES_ProductTask_Rest]
	@TaskAID bigint,
	@optor nvarchar(50)
AS 
BEGIN
	declare @操作时间 datetime=getdate();
	declare @词条名称 nvarchar(50)='暂停'
	declare @数据类别 nvarchar(50)='生产操作'
	declare @词条ID int=-1
	select @词条ID=词条编号 from YL_基础表_数据字典 where 词条名称=@词条名称 and 数据类别=@数据类别

	--更新收料数量、收料状态、可执行状态
	Update MES_接口_生产计划_生产任务 set 加工状态=@词条ID where AID=@TaskAID --该工作所有在加工任务

	--生成操作记录
	EXEC [dbo].[MES_ProductCenter_OptRecord_Save]
		@dicItemName = @词条名称,
		@dataType = @数据类别,
		@TaskAID = @TaskAID,
		--@optCount = @checkResult,  --操作数值
		--@optDescription = @词条名称,
		@optor = @optor,
		@optTime = @操作时间
END
GO
/****** Object:  StoredProcedure [dbo].[MES_ProductTask_SendInspection]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[MES_ProductTask_SendInspection]
	@TaskAID bigint,
	@recievCount int,
	@optor nvarchar(50)
AS
declare @操作时间 datetime=getdate()
declare @任务状态 int
declare @完成数量 int
declare @分配数量 int
declare @订单编号 int
declare @工位名称 nvarchar(50)
BEGIN


	Update MES_接口_生产计划_生产任务 
	set 完成数量=isnull(完成数量,0)+@recievCount,
	修改时间 = @操作时间
	where AID=@TaskAID
	select @分配数量 = 指派数量,@完成数量 = 完成数量, @订单编号 = 订单编号,@工位名称 = 指派对象 from MES_接口_生产计划_生产任务 where AID=@TaskAID
	if(@完成数量 = @分配数量)
	begin
		Update MES_接口_生产计划_生产任务 
		set 任务状态 = 4,
		修改时间 = @操作时间
		where AID=@TaskAID
	end
	--生成操作记录
	declare @词条名称 nvarchar(50)='报工'
	declare @数据类别 nvarchar(50)='生产操作'
	declare @dicItemID int
    declare @HTCode nvarchar(50)
    declare @OrderNo int
    declare @PartCode nvarchar(50)
    declare @PartName nvarchar(50)
    declare @OPCode nvarchar(50)
    declare @OPName nvarchar(50)
    declare @StageFlag nvarchar(50)
    declare @ProcessName nvarchar(50)
    declare @AssembleType nvarchar(50)
    
    -- 新增用于工时计算的变量
    declare @cycleStartTime datetime
    declare @cycleEndTime datetime
    declare @totalWorkSeconds int = 0
    
    select @dicItemID=词条编号 from YL_基础表_数据字典 where 词条名称=@词条名称 and 数据类别=@数据类别
    select @HTCode=[合同号],@OrderNo=[订单编号],@OPCode=[指派对象编号],@OPName=[指派对象],@PartCode=[物料编号],@PartName=[物料描述],@StageFlag=[阶段标识],@ProcessName=[工序名称],@AssembleType=[不装配]
    from View_生产订单_MES where TaskAID=@TaskAID
    
    -- 插入操作记录
    INSERT INTO [dbo].[YL_加工中心_操作记录表]
           ([操作类别编号]
           ,[操作类别]
           ,[阶段标识]
           ,[工序名称]
           ,[工位编号]
           ,[工位名称]
           ,[操作人]
           ,[合同号]
           ,[订单编号]
           ,[物料编号]
           ,[物料描述]
           ,[操作数值]
           ,[操作内容]
           ,[操作描述]
           ,TaskAID
           ,[开始时间]
           ,[不装配]
		   ,最后编辑时间)
    Values(@dicItemID
          ,@词条名称
          ,@StageFlag
          ,@ProcessName
          ,@OPCode
          ,@OPName
          ,@optor
          ,@HTCode
          ,@OrderNo
          ,@PartCode
          ,@PartName
          ,@recievCount
          ,@词条名称
          ,''
          ,@TaskAID
          ,@操作时间
          ,@AssembleType
		  ,@操作时间
        )
	--EXEC	[dbo].[MES_ProductCenter_OptRecord_Save]
	--	@dicItemName = @词条名称,
	--	@dataType = @数据类别,
	--	@TaskAID = @TaskAID,
	--	@optCount = @recievCount,
	--	--@optDescription = N'Description',
	--	@optor = @optor,
	--	@optTime = @操作时间
	INSERT INTO [dbo].[YL_加工中心_报工记录]
		([班次],[操作人],[工时类型],[报工数量],[工时],[订单编号],[TaskAID],[报工时间],[工位名称])
	VALUES('装配',@optor,'生产工时',0,0,@订单编号,@TaskAID,GETDATE(),@工位名称)


END
GO
/****** Object:  StoredProcedure [dbo].[MES_ProductTask_WorkingStart]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[MES_ProductTask_WorkingStart]
	@TaskAID bigint,
	@optor nvarchar(50),
	@收料 int,
	@分配数 int
	
AS
BEGIN
	declare @操作时间 datetime=getdate()
	declare @任务状态 int=-1  --0待执行，1可执行，2已开工，4已完成。
	declare @开工 int=-1
	declare @词条名称 nvarchar(50)='开始加工'
	declare @数据类别 nvarchar(50)='生产操作'
	declare @词条ID int=-1

	select @任务状态=isnull(任务状态,0),@开工=isnull(开工,0) from View_生产订单_MES where TaskAID=@TaskAID
	select @词条ID=词条编号 from YL_基础表_数据字典 where 词条名称=@词条名称 and 数据类别=@数据类别

	--1、第一次【开始加工】时，任务状态从【1待执行】-->【2已开工】（只有1待执行的任务，开工时才需要变任务状态为2）
	--2、后续点击【开始加工】不会改变任务状态，只是记录事件记录（统计工时用）
	--3、直到报工累计数量等于分配数时，任务状态从【2已开工】-->【4已完成】
	if(@任务状态 = 1) --可执行任务
		begin
			--更新可执行状态
			Update MES_接口_生产计划_生产任务 set  任务状态=2,可执行=1,开工=1,加工状态=@词条ID,开工时间=@操作时间,操作时间=@操作时间 where AID=@TaskAID
		end
	if(@任务状态 = 2) --可执行任务
		begin
			--更新可执行状态
			Update MES_接口_生产计划_生产任务 set  任务状态=2,可执行=1,开工=1,加工状态=@词条ID,开工时间=@操作时间,操作时间=@操作时间 where AID=@TaskAID
		end
	declare @订单编号 int=-1
	declare @订单行号 int=-1
	declare @合格数 int=0
	select @订单编号=[订单编号],@订单行号 = 订单行号 FROM [View_生产订单_MES] where TaskAID=@TaskAID
	SELECT @合格数 = 合格数 
          FROM [dbo].[YL_质量检验_质检记录] qc
          INNER JOIN [View_生产订单_MES] vt ON qc.TaskAID = vt.TaskAID
          WHERE vt.[订单行号] = @订单行号-1
			and vt.订单编号 = @订单编号
			AND qc.检测类型编号 = '6'
	if(@收料<>@合格数 and @订单行号>1)
		begin
			--更新收料数量
			Update MES_接口_生产计划_生产任务 set 收料 = 1,收料数量 = @合格数, 操作时间=@操作时间 where AID=@TaskAID
		end
	if(@收料<>@合格数 and @订单行号=1)
		begin
			--更新收料数量
			Update MES_接口_生产计划_生产任务 set 收料 = 1,收料数量 = @分配数 , 操作时间=@操作时间 where AID=@TaskAID
		end
	--if(@任务状态 > 1) 
	--	begin
	--		--非首次开始加工，只改变当前加工状态
	--		Update MES_接口_生产计划_生产任务 set 加工状态=@词条ID,操作时间=@操作时间 where AID=@TaskAID
	--	end
	--生成操作记录
	EXEC [dbo].[MES_ProductCenter_OptRecord_Save]
		@dicItemName = @词条名称,
		@dataType = @数据类别,
		@TaskAID = @TaskAID,
		--@optCount = @recievCount,
		--@optDescription = N'Description',
		@optor = @optor,
		@optTime = @操作时间

END
GO
/****** Object:  StoredProcedure [dbo].[MES_ProductTask_WorkTimeSum]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[MES_ProductTask_WorkTimeSum]
	@计划开工_Start nvarchar(50)='',
	@计划开工_End nvarchar(50)=''
AS
select TaskAID,工序名称,sum(工时) as 总工时 from YL_加工中心_操作记录表 where 工时 >0 group by TaskAID,工序名称

GO
/****** Object:  StoredProcedure [dbo].[MES_QualityInspection_CheckRecord_Query]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[MES_QualityInspection_CheckRecord_Query]
    @计划号 NVARCHAR(100) = '',
    @零件编码 NVARCHAR(200) = '',
    @工艺编号 NVARCHAR(50) = '',
    @检测类型编号 INT = -1,  -- 主要参数：1=首检自检, 3=序检自检, 6=收检
    @检验结果 NVARCHAR(10) = '',
    @检测人 NVARCHAR(50) = '',
    @检测时间开始 DATETIME = NULL,
    @检测时间结束 DATETIME = NULL
AS
BEGIN
    SET NOCOUNT ON;

    -- 构建动态SQL查询语句
    DECLARE @SQL NVARCHAR(MAX) = '
        SELECT  top 100
            a.[QT_AID],
            a.[TaskAID],
            a.[检测类型编号],
            a.[质检类型],
            a.[零件名称],
            a.[内部合同号],
            a.[零件编码],
            a.[计划号],
            a.[工序名称],
            b.[工艺编号],
            a.[检验数量],
            a.[合格数],
            a.[不合格数],
            a.[检测人],
            a.[检测时间],
            a.[计划生产数],
            a.[检测说明],
            CASE 
                WHEN a.[不合格数] = 0 AND a.[合格数] > 0 THEN ''合格''
                WHEN a.[不合格数] > 0 THEN ''不合格''
                ELSE ''未判定''
            END AS 检验结果
        FROM [dbo].[YL_质量检验_质检记录] a 
        LEFT JOIN [dbo].[基础表_工序] b ON a.[工序名称] = b.[工序名称]
        WHERE 质检类型 <> ''来料检验''
    '

    -- 添加查询条件（修复空值处理）
    IF ISNULL(@计划号, '') <> ''
        SET @SQL = @SQL + ' AND a.[计划号]  =  ''' + @计划号 + ''''

    IF ISNULL(@零件编码, '') <> ''
        SET @SQL = @SQL + ' AND a.[零件编码] LIKE ''%' + @零件编码 + '%'''

    -- 检测类型编号查询条件（修复-1的处理）
    IF @检测类型编号 IS NOT NULL AND @检测类型编号 > 0
        SET @SQL = @SQL + ' AND a.[检测类型编号] = ' + CAST(@检测类型编号 AS NVARCHAR(10))

    -- 工艺编号查询条件（修复空值处理）
    IF ISNULL(@工艺编号, '') <> ''
    BEGIN
        SET @SQL = @SQL + ' AND EXISTS (
            SELECT 1 FROM [dbo].[基础表_工序] b2 
            WHERE b2.[工艺编号] = ''' + @工艺编号 + ''' 
            AND b2.[工序名称] = a.[工序名称]
        )'
    END

    -- 检验结果处理（修复空值处理）
    IF ISNULL(@检验结果, '') <> ''
    BEGIN
        IF @检验结果 = '1'  -- 合格
            SET @SQL = @SQL + ' AND a.[不合格数] = 0 AND a.[合格数] > 0'
        ELSE IF @检验结果 = '0'  -- 不合格
            SET @SQL = @SQL + ' AND a.[不合格数] > 0'
    END

    IF ISNULL(@检测人, '') <> ''
        SET @SQL = @SQL + ' AND a.[检测人] LIKE ''%' + @检测人 + '%'''

    -- 时间条件处理
    --DECLARE @Params NVARCHAR(1000) = N'@检测时间开始Param DATETIME, @检测时间结束Param DATETIME'
    
    --IF @检测时间开始 IS NOT NULL
    --    SET @SQL = @SQL + ' AND a.[检测时间] >= @检测时间开始Param'
    --ELSE
    --    -- 如果没有提供开始时间，默认查询最近一年的数据
    --    SET @SQL = @SQL + ' AND a.[检测时间] >= DATEADD(YEAR, -1, GETDATE())'
    
    --IF @检测时间结束 IS NOT NULL
    --    SET @SQL = @SQL + ' AND a.[检测时间] <= @检测时间结束Param'

    -- 添加排序
    SET @SQL = @SQL + ' ORDER BY a.[检测时间] DESC'

    PRINT '生成的SQL: ' + @SQL  -- 调试用

    -- 设置默认时间值（如果为空）
    IF @检测时间开始 IS NULL
        SET @检测时间开始 = DATEADD(YEAR, -1, GETDATE())
        
    IF @检测时间结束 IS NULL
        SET @检测时间结束 = GETDATE()

    -- 执行查询
    EXEC sp_executesql @SQL
        --@Params,
        --@检测时间开始Param = @检测时间开始,
        --@检测时间结束Param = @检测时间结束
END
GO
/****** Object:  StoredProcedure [dbo].[MES_QualityInspection_GetInspectionDetails]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- 获取检测零件对应的详细检测数据
CREATE PROCEDURE [dbo].[MES_QualityInspection_GetInspectionDetails]
    @LJ_AID BIGINT
AS
BEGIN
    SET NOCOUNT ON;
    
    SELECT 
        AID,
        LJ_AID,
        物料编号,
        当前检测零件编号,
        阶段标识,
        工序名称,
        计划号,
        检测项目,
        理论值,
        上限值,
        下限值,
        实测值,
        测量单位,
        检验比例,
        检具,
        检测结果,
        合格数,
        不合格数,
        备注,
        检测人,
        检测时间,
        CASE 
            WHEN 检测结果 = 1 THEN '合格'
            WHEN 检测结果 = 0 THEN '不合格'
            ELSE '未判定'
        END AS 检测结果描述
    FROM [dbo].[YL_质量检验_质检记录_检测数据]
    WHERE LJ_AID = @LJ_AID
    ORDER BY AID;
END
GO
/****** Object:  StoredProcedure [dbo].[MES_QualityInspection_GetInspectionParts]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 获取质检记录对应的检测零件列表
CREATE PROCEDURE [dbo].[MES_QualityInspection_GetInspectionParts]
    @QT_AID BIGINT
AS
BEGIN
    SET NOCOUNT ON;
    
    SELECT 
        LJ_AID,
        QT_AID,
        当前检测零件编号,
        检测结果,
        检测时间,
        检测人,
        零件编号,
        CASE 
            WHEN 检测结果 = 1 THEN '合格'
            WHEN 检测结果 = 0 THEN '不合格'
            ELSE '未判定'
        END AS 检测结果描述
    FROM [dbo].[YL_质量检验_质检记录_检测零件]
    WHERE QT_AID = @QT_AID
    ORDER BY 当前检测零件编号;
END
GO
/****** Object:  StoredProcedure [dbo].[MES_QulityInspection_CheckItemData_Save]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<保存检测项数据并更新质检记录 - 支持批量零件检测>
-- =============================================
CREATE PROCEDURE [dbo].[MES_QulityInspection_CheckItemData_Save]
  -- YL_质量检验_质检记录_检测数据所需参数
	@TaskAID bigint = -1,
	@物料编号 nvarchar(100)= '',
	@阶段标识 int = -1,
	@工序名称 nvarchar(100)= '',
	@计划号 int = -1,
	@检测项目 nvarchar(500) = '',
	@理论值 nvarchar(50)= '',
	@上限值 nvarchar(50)= '',
	@下限值 nvarchar(50)= '',
	@实测值 nvarchar(50)= '',
	@测量单位 nvarchar(50)= '',
	@检验比例 nvarchar(50)= '',
	@检具 nvarchar(50)= '',
	@检测结果 int = -1,
	@合格数 int = -1,
	@不合格数 int= -1,
	@备注 nvarchar(200)= '',
	@检测人 nvarchar(50)= '',
	@检测时间 datetime = null,
	@当前检测零件编号 int = -1,
	-- 新增YL_质量检验_质检记录所需参数
	@质检类型 nvarchar(100) = '',
	@检测类型编号 nvarchar(100) = '',
	@零件名称 nvarchar(100) = '',
	@内部合同号 nvarchar(100) = '',
	@零件编码 nvarchar(100) = '',
	@检验数量 int = -1,
	@计划生产数 int = -1,
	@检测说明 nvarchar(500) = '',
	@QT_AID BIGINT = -1 OUTPUT,  -- 改为OUTPUT参数，用于返回主记录ID
	@LJ_AID BIGINT = -1 OUTPUT   -- 改为OUTPUT参数，用于返回零件记录ID
AS
BEGIN
	SET NOCOUNT ON;

	BEGIN TRY
		BEGIN TRANSACTION;
		
		DECLARE @ExistingQT_AID BIGINT;
		DECLARE @ExistingLJ_AID BIGINT;
		DECLARE @CurrentQualifiedCount INT = 0;
		DECLARE @CurrentUnqualifiedCount INT = 0;
		DECLARE @CurrentInspectionCount INT = 0;
		DECLARE @PartResult INT = 1; -- 零件结果，默认合格

		-- 1. 首先处理YL_质量检验_质检记录（主记录）
		-- 查找是否已存在相同批次的质检记录
		SELECT @ExistingQT_AID = QT_AID 
		FROM [dbo].[YL_质量检验_质检记录] 
		WHERE TaskAID = @TaskAID 
		  AND 零件编码 = @零件编码 
		  AND 工序名称 = @工序名称 
		  AND 质检类型 = @质检类型
		  AND 检测人 = @检测人
		  AND CONVERT(DATE, 检测时间) = CONVERT(DATE, @检测时间);

		IF @ExistingQT_AID IS NULL
		BEGIN
			-- 插入新记录
			INSERT INTO [dbo].[YL_质量检验_质检记录](
				TaskAID, 质检类型, 检测类型编号, 零件名称, 内部合同号, 
				零件编码, 计划号, 工序名称, 检验数量, 合格数, 不合格数, 
				检测人, 检测时间, 计划生产数, 检测说明
			)
			VALUES (
				@TaskAID, @质检类型, @检测类型编号, @零件名称, @内部合同号, 
				@零件编码, @计划号, @工序名称, @检验数量, @合格数, @不合格数, 
				@检测人, @检测时间, @计划生产数, @检测说明
			);
			SET @QT_AID = SCOPE_IDENTITY();
			SET @ExistingQT_AID = @QT_AID;
		END
		ELSE 
		BEGIN
			-- 更新现有记录 - 累加合格数和不合格数
			SELECT 
				@CurrentQualifiedCount = 合格数,
				@CurrentUnqualifiedCount = 不合格数,
				@CurrentInspectionCount = 检验数量
			FROM [dbo].[YL_质量检验_质检记录] 
			WHERE QT_AID = @ExistingQT_AID;

			-- 累加数值
			SET @CurrentQualifiedCount = @CurrentQualifiedCount + @合格数;
			SET @CurrentUnqualifiedCount = @CurrentUnqualifiedCount + @不合格数;
			SET @CurrentInspectionCount = @CurrentInspectionCount + @检验数量;

			UPDATE [dbo].[YL_质量检验_质检记录]
			SET 
				检验数量 = @CurrentInspectionCount,
				合格数 = @CurrentQualifiedCount,
				不合格数 = @CurrentUnqualifiedCount,
				检测时间 = GETDATE() -- 更新检测时间为当前时间
			WHERE QT_AID = @ExistingQT_AID;
			
			SET @QT_AID = @ExistingQT_AID;
		END

		  -- 2. 关键修改：处理YL_质量检验_质检记录_检测零件（零件记录）
        -- 修改判断条件，加入当前检测零件编号
        SELECT @ExistingLJ_AID = LJ_AID 
        FROM [dbo].[YL_质量检验_质检记录_检测零件] 
        WHERE QT_AID = @ExistingQT_AID 
          AND 零件编号 = @零件编码
          AND 当前检测零件编号 = @当前检测零件编号; -- 增加这个条件

        IF @检测结果 = 0
        BEGIN
            SET @PartResult = 0;
        END

        -- 如果不存在该零件编号的检测记录，始终插入新记录
        IF @ExistingLJ_AID IS NULL
        BEGIN
            INSERT INTO [dbo].[YL_质量检验_质检记录_检测零件](
               QT_AID, 检测结果, 检测时间, 检测人, 零件编号, 当前检测零件编号
            )
            VALUES(
               @ExistingQT_AID, @PartResult, @检测时间, @检测人, @零件编码, @当前检测零件编号
            );
            SET @LJ_AID = SCOPE_IDENTITY();
        END
        ELSE
        BEGIN
            -- 如果已存在，更新记录（覆盖原有数据）
            UPDATE [dbo].[YL_质量检验_质检记录_检测零件]
            SET 检测结果 = @PartResult,
                检测时间 = @检测时间
            WHERE LJ_AID = @ExistingLJ_AID;
            SET @LJ_AID = @ExistingLJ_AID;
        END

		-- 3. 插入检测数据到YL_质量检验_质检记录_检测数据表
		 IF (@QT_AID > 0 AND @LJ_AID > 0)
        BEGIN
            -- 调试信息：检查参数值
            PRINT 'QT_AID: ' + CAST(@QT_AID AS NVARCHAR(20));
            PRINT 'LJ_AID: ' + CAST(@LJ_AID AS NVARCHAR(20));
            PRINT '检测项目: ' + @检测项目;
            PRINT '当前检测零件编号: ' + CAST(@当前检测零件编号 AS NVARCHAR(20));
            
            -- 修复判断逻辑：简化条件，确保第一条数据能插入
            DECLARE @ExistingDataID BIGINT;
            
            SELECT @ExistingDataID = AID 
            FROM [dbo].[YL_质量检验_质检记录_检测数据] 
            WHERE LJ_AID = @LJ_AID 
              AND 检测项目 = @检测项目
              AND 当前检测零件编号 = @当前检测零件编号;

            IF @ExistingDataID IS NULL
            BEGIN
                -- 插入新记录
                INSERT INTO [dbo].[YL_质量检验_质检记录_检测数据](
                    LJ_AID, 检测项目, 理论值, 上限值, 下限值, 
                    测量单位, 实测值, 检测结果, 检验比例, 检具, 备注, 
                    物料编号, 阶段标识, 工序名称, 计划号, 合格数, 
                    检测人, 检测时间, 不合格数, 当前检测零件编号
                )
                VALUES (
                    @LJ_AID, @检测项目, @理论值, @上限值, @下限值, 
                    @测量单位, @实测值, @检测结果, @检验比例, @检具, @备注, 
                    @物料编号, @阶段标识, @工序名称, @计划号, @合格数, 
                    @检测人, @检测时间, @不合格数, @当前检测零件编号
                );
                
                PRINT '插入新检测数据记录';
            END
            ELSE
            BEGIN
                -- 更新现有记录
                UPDATE [dbo].[YL_质量检验_质检记录_检测数据]
                SET 实测值 = @实测值,
                    检测结果 = @检测结果,
                    检测时间 = @检测时间,
                    合格数 = @合格数,
                    不合格数 = @不合格数,
                    备注 = @备注
                WHERE AID = @ExistingDataID;
                
                PRINT '更新现有检测数据记录，AID: ' + CAST(@ExistingDataID AS NVARCHAR(20));
            END
        END
        ELSE
        BEGIN
            -- 如果QT_AID或LJ_AID无效，抛出错误
            RAISERROR('主记录或零件记录创建失败', 16, 1);
        END

        COMMIT TRANSACTION;
        
        SELECT 1 AS 执行结果, '数据保存成功' AS 消息, @QT_AID AS QT_AID, @LJ_AID AS LJ_AID;
        
    END TRY
    BEGIN CATCH
        IF @@TRANCOUNT > 0
            ROLLBACK TRANSACTION;
        
        SELECT 0 AS 执行结果, 
               '保存失败: ' + ERROR_MESSAGE() AS 消息,
               ERROR_LINE() AS 错误行号,
               ERROR_NUMBER() AS 错误编号,
               -1 AS QT_AID,
               -1 AS LJ_AID;
    END CATCH
END
GO
/****** Object:  StoredProcedure [dbo].[MES_QulityInspection_FinalCheck]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[MES_QulityInspection_FinalCheck]
    @TaskAID INT = 0,
    @检测类型编号 INT = 8,
    @质检类型 NVARCHAR(50) = '终检',
    @零件名称 NVARCHAR(100),
    @内部合同号 NVARCHAR(100),
    @零件编码 NVARCHAR(100),
    @计划号 NVARCHAR(100),
    @工序名称 NVARCHAR(100),
    @检测数量 INT,
    @合格数 INT,
    @不合格数 INT,
    @检测人 NVARCHAR(50),
    @检测时间 NVARCHAR(50),
    @检测说明 NVARCHAR(500) = '',
	@放行数量 INT = 0
AS
BEGIN
    SET NOCOUNT ON;


        -- 直接插入新记录，不再检查是否存在，允许同一条数据有多条终检记录
        INSERT INTO [dbo].[YL_质量检验_质检记录] (
            TaskAID, 检测类型编号, 质检类型, 零件名称, 内部合同号, 
            零件编码, 计划号, 工序名称, 检验数量, 合格数, 
            不合格数, 检测人, 检测时间, 检测说明,行号,订单类型,放行数量
        )
        VALUES (
            @TaskAID, @检测类型编号, @质检类型, @零件名称, @内部合同号,
            @零件编码, @计划号, @工序名称, @检测数量, @合格数,
            @不合格数, @检测人, @检测时间, @检测说明,1,'202-59',@放行数量
        )

        -- 返回成功结果
        SELECT '1' AS result

END
GO
/****** Object:  StoredProcedure [dbo].[MES_QulityInspection_FirstCheckRecords]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[MES_QulityInspection_FirstCheckRecords]
	@ProcessID int=-1,
	@OPCode nvarchar(50)='',
	@OrderNo int=-1,
	@PartCode nvarchar(50)='',
	@PlanStart nvarchar(50)='',
	@PlanEnd nvarchar(50)='',
	@不装配 int =-1  --1自制件，2装配件
AS
BEGIN


declare @whereString nvarchar(max)=' where 操作类别=''首检'''
declare @orderString nvarchar(max)=' order by 开始时间 desc'
declare @sqlString nvarchar(max)='
	SELECT [操作类别]
		,[阶段标识]
		,[工序名称]
		,[工位编号]
		,[工位名称]
		,[操作人]
		,[合同号]
		,[订单编号]
		,[物料编号]
		,[物料描述]
		,case when [操作数值]=1 then ''OK'' else ''NG'' end as 操作数值
		,[操作内容]
		,[操作描述]
		,[TaskAID]
		,[开始时间]
		,[结束时间]
		,[工时]

	FROM [YL_加工中心_操作记录表]';

if(@ProcessID>0) set @whereString=@whereString+' and [阶段标识]='+Convert(VARCHAR(10),@ProcessID)
if(len(@OPCode)>0) set @whereString=@whereString+' and [工位编号] = '''+@OPCode+''''
if(@OrderNo>0) set @whereString=@whereString+' and [订单编号]='+Convert(VARCHAR(10),@OrderNo)
if(len(@PartCode)>0) set @whereString=@whereString+' and [物料编号] like ''%'+@PartCode+'%'''
if(len(@PlanStart)>0) set @whereString=@whereString+' and [开始时间] >= '''+Convert(VARCHAR(50),@PlanStart)+''''
if(len(@PlanEnd)>0) set @whereString=@whereString+' and [开始时间] <= '''+Convert(VARCHAR(50),DATEADD(day,1, @PlanEnd))+''''
if(@不装配=1)set @whereString=@whereString+' and [不装配] <> ''否'''
if(@不装配=2)set @whereString=@whereString+' and [不装配] = ''否'''

set @sqlString=@sqlString+@whereString+@orderString
print @sqlString
EXEC sp_executesql @sqlString

END
GO
/****** Object:  StoredProcedure [dbo].[MES_QulityInspection_GetCheckCount]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[MES_QulityInspection_GetCheckCount]
	@TaskAID int=-1,
	@CheckType varchar(10)
AS
declare @whereStr nvarchar(max)=' where '  
declare @selStr nvarchar(max)='select isnull(sum(检验数量),0) as 检验数量 from YL_质量检验_质检记录';
if(@TaskAID>0)set @whereStr=@whereStr + ' TaskAID = '+Convert(VARCHAR(10),@TaskAID)
if(@CheckType <>'')set @whereStr=@whereStr +  ' and 质检类型 = '''+@CheckType+''' '
set @selStr=@selStr+@whereStr
print @selStr
EXEC sp_executesql @selStr
GO
/****** Object:  StoredProcedure [dbo].[MES_QulityInspection_GetItemStandard]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[MES_QulityInspection_GetItemStandard]
	@物料编号 nvarchar(50)= NULL,
	@工序名称编号 int=-1,
	@检测类别编号 int=-1
AS
SELECT [物料编号]
      ,[工序名称编号]
      ,[检测项目]
      ,[理论值]
      ,[上限值]
      ,[下限值]
      ,[测量单位]
	  ,[检验比例]
      ,[检具]
      ,[备注]
	  ,[检测类别编号]
  FROM [YL_质量检验_检测标准]
  where [物料编号]=@物料编号 and [工序名称编号]=@工序名称编号 and [检测类别编号]=@检测类别编号
GO
/****** Object:  StoredProcedure [dbo].[MES_QulityInspection_GetPart]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[MES_QulityInspection_GetPart]
	@QT_AID int=-1
AS
declare @whereStr nvarchar(max)=' where '  --已开工、已完成的任务
declare @selStr nvarchar(max)='
	SELECT [AID]
      ,[QT_AID]
      ,[零件序号]
      ,[NG号]
      ,[检测结果]
      ,[检测时间]
      ,[检测人]
      ,[零件编号]
  FROM [dbo].[YL_质量检验_质检记录_检测零件] ';

	if(@QT_AID>0)set @whereStr=@whereStr + ' [QT_AID]='+Convert(VARCHAR(10),@QT_AID)
	set @selStr=@selStr+@whereStr+' order by [检测时间] DESC'
print @selStr
EXEC sp_executesql @selStr
GO
/****** Object:  StoredProcedure [dbo].[MES_QulityInspection_GetTask]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[MES_QulityInspection_GetTask]
	@阶段标识 int=-1,
	@工位编号 nvarchar(50)='',
	@合同号 nvarchar(50)='',
	@订单号 int=-1,
	@零件编号 nvarchar(50)='',
	@零件名称 nvarchar(50)='',
	@完工日期_Start nvarchar(50)='',
	@完工日期_End nvarchar(50)='',
	@已首检 int=-1,
	@已巡检 int=-1,
	@已序检 int=-1,
	@检测时间_Start nvarchar(50)='',
	@检测时间_End nvarchar(50)='',
	@任务状态 int=-1,	--0待执行、1可执行、2已开工、4已完工
	@不装配 int=-1   --1自制件，2装配件

AS
declare @whereStr nvarchar(max)=' where 任务状态>=2'  --已开工、已完成的任务
declare @selStr nvarchar(max)='
	SELECT [订单编号]
		  ,[合同号]
		  ,[订单拆分内码]
		  ,[物料编号]
		  ,[物料描述]
		  ,[工序计划数量]
		  ,[加急状态]
		  ,[优先级]
		  ,[阶段标识]
		  ,[工序名称]
		  ,[顺序编号]
		  ,[不装配]
		  ,[指派对象编号]
		  ,[指派对象]
		  ,[指派数量]
		  ,[计划开始时间]
		  ,[计划完成时间]
		  ,[最晚开始时间]
		  ,[派工状态]
		  ,case when isnull(任务状态,0)=4 then ''已完成'' 
		  when isnull(任务状态,0)=2 then ''已开工'' 
		  when isnull(任务状态,0)=1 and isnull([收料],0)=0 then ''待执行'' 
		  when isnull(任务状态,0)=1 and isnull([收料],0)=1 then ''可执行'' 
		  else '''' end as [任务状态]
		  ,[派工特殊说明]
		  ,[最后编辑人]
		  ,[最后编辑时间]
		  ,[完成数量]
		  ,isnull([首检],0) as [首检]
		  ,isnull([巡检],0) as [巡检]
		  ,isnull([序检],0) as [序检]
		  ,[TaskAID]
		  ,[开工时间]
		  ,[完工时间]
		  ,isnull([不合格数量],0) as [不合格数量]
		  ,isnull([让步放行数量],0) as [让步放行数量]
		  ,isnull([报废数量],0) as [报废数量]
		  ,(isnull([完成数量],0) - isnull([不合格数量],0) - isnull([报废数量],0) - isnull([让步放行数量],0) ) as 合格数量
		   ,(isnull([完成数量],0) - isnull((isnull([完成数量],0) - isnull([不合格数量],0) - isnull([报废数量],0) - isnull([让步放行数量],0) ),0) - isnull([不合格数量],0) ) as 未检数量
		  ,[首检]
		  ,[巡检]
		  
	  FROM [View_生产订单_MES]';

	if(@阶段标识>0)set @whereStr=@whereStr + ' and [阶段标识]='+Convert(VARCHAR(10),@阶段标识)
	if(len(@工位编号)>0)set @whereStr=@whereStr + ' and [指派对象编号]='''+@工位编号+''''
	if(len(@合同号)>0)set @whereStr=@whereStr + ' and [合同号] like ''%'+@合同号+'%'''
	if(@订单号>0)set @whereStr=@whereStr + ' and [订单编号]='+Convert(VARCHAR(10),@订单号)
	if(len(@零件编号)>0)set @whereStr=@whereStr + ' and [物料编号] like ''%'+@零件编号+'%'''
	if(len(@零件名称)>0)set @whereStr=@whereStr + ' and [物料描述] like ''%'+@零件名称+'%'''
	if(@完工日期_Start<>'')set @whereStr=@whereStr + ' and [计划完成时间] >= '''+@完工日期_Start+''''
	if(@完工日期_End<>'')set @whereStr=@whereStr + ' and [计划完成时间] <= '''+@完工日期_End+''''
	if(@已首检=1)set @whereStr=@whereStr + ' and isnull([首检],0)=1'
	else if(@已首检=0) set @whereStr=@whereStr + ' and isnull([首检],0)=0'
	if(@已巡检=1)set @whereStr=@whereStr + ' and isnull([巡检],0)=1'
	else if(@已巡检=0) set @whereStr=@whereStr + ' and isnull([巡检],0)=0'
	if(@已序检=1)set @whereStr=@whereStr + ' and isnull([序检],0)=1'
	else if(@已序检=0) set @whereStr=@whereStr + ' and isnull([序检],0)=0'
	if(@检测时间_Start<>'')set @whereStr=@whereStr + ' and [计划完成时间] >= '''+@检测时间_Start+''''
	if(@检测时间_End<>'')set @whereStr=@whereStr + ' and [计划完成时间] <= '''+@检测时间_End+''''
	if(@任务状态>=0)set @whereStr=@whereStr + ' and [任务状态] = '+Convert(VARCHAR(10),@任务状态)
	if(@不装配=1)set @whereStr=@whereStr + ' and [不装配] <> ''否'''
	if(@不装配=2)set @whereStr=@whereStr + ' and [不装配] = ''否'''

	set @selStr=@selStr+@whereStr+' order by [计划开始时间],[订单编号],[阶段标识]'
print @selStr
EXEC sp_executesql @selStr
GO
/****** Object:  StoredProcedure [dbo].[MES_QulityInspection_MeasuringTool]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[MES_QulityInspection_MeasuringTool]
	@量具编号 nvarchar(50)='',
	@量具名称 nvarchar(50)='',
	@规格型号 nvarchar(50)='',
	@制造商 nvarchar(50)='',
	@量具状态 nvarchar(50)='',
	@负责人 nvarchar(50)=''
AS

declare @whereStr nvarchar(max)=' where 1=1'
declare @selStr nvarchar(max)='
  SELECT [AID]
      ,[量具编号]
      ,[量具名称]
      ,[规格型号]
      ,[制造商]
      ,[精度等级]
      ,[测量范围]
      ,[量具状态]
      ,[负责人]
      ,[使用寿命]
  FROM [dbo].[YL_质量检验_量具信息]';

if(@量具编号<>'')set @whereStr=@whereStr + ' and [量具编号] like ''%'+@量具编号+'%'''
if(@量具名称<>'')set @whereStr=@whereStr + ' and [量具名称] like ''%'+@量具名称+'%'''
if(@规格型号<>'')set @whereStr=@whereStr + ' and [量具编号] like ''%'+@规格型号+'%'''
if(@制造商<>'')set @whereStr=@whereStr + ' and [制造商] like ''%'+@制造商+'%'''
if(@制造商<>'')set @whereStr=@whereStr + ' and [制造商] like ''%'+@制造商+'%'''
if(@量具状态<>'')set @whereStr=@whereStr + ' and [量具状态] like ''%'+@量具状态+'%'''
if(@负责人<>'')set @whereStr=@whereStr + ' and [负责人] like ''%'+@负责人+'%'''

set @selStr=@selStr+@whereStr+' order by [量具名称]'
print @selStr
EXEC sp_executesql @selStr
GO
/****** Object:  StoredProcedure [dbo].[MES_QulityInspection_NGPart_Add]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[MES_QulityInspection_NGPart_Add]
    @TaskAID INT = NULL,
    @不合格数量 INT = NULL,
    @申请让步放行 INT = NULL,
    @申请内容 NVARCHAR(2000) = NULL,
    @发起人ID INT = NULL,
    @接收人ID INT = NULL
AS
BEGIN
    SET NOCOUNT ON;
    
    -- 插入新记录
    INSERT INTO [dbo].[YL_质量检验_不合格品处理] (
        [TaskAID],
        [不合格数量],
        [申请让步放行],
        [申请内容],
        [发起人ID],
        [发起时间]
    )
    VALUES (
        @TaskAID,
        @不合格数量,
        @申请让步放行,
        @申请内容,
        @发起人ID,
        getdate()
    );

	--插入流程节点
	declare @flowAID int=SCOPE_IDENTITY();
    EXEC [dbo].[MES_QulityInspection_NGPart_FlowNode_Add]
		@FlowAID = @flowAID,
		@处理人ID = @接收人ID,
		@让步放行数量 = @申请让步放行
END
GO
/****** Object:  StoredProcedure [dbo].[MES_QulityInspection_NGPart_Finish]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [dbo].[MES_QulityInspection_NGPart_Finish]
    @FlowAID INT = NULL
AS
BEGIN
    -- 插入新记录
	UPDATE [dbo].[YL_质量检验_不合格品处理] SET [结束时间]=getdate() where [FlowAID]=@FlowAID
END
GO
/****** Object:  StoredProcedure [dbo].[MES_QulityInspection_NGPart_FlowNode_Add]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[MES_QulityInspection_NGPart_FlowNode_Add]
    @FlowAID INT,
    @处理人ID INT = NULL,
    @让步放行数量 INT = NULL
AS
BEGIN
    SET NOCOUNT ON;
    Declare @接收时间 DATETIME = GETDATE();
    Declare @NewFlowNodeID int=-1;
    SELECT @NewFlowNodeID=isnull(max([FlowNodeID]),0)+1 FROM [YL_质量检验_不合格品处理_处理节点] where FlowAID=@FlowAID

    -- 检查FlowAID是否已存在（主键冲突）
    BEGIN
        -- 如果不存在则插入新记录
        INSERT INTO [dbo].[YL_质量检验_不合格品处理_处理节点] (
            [FlowAID],
			[FlowNodeID],
            [处理人ID],
            [接收时间],
            [让步放行数量]
        )
        VALUES (
            @FlowAID,
			@NewFlowNodeID,
            @处理人ID,
            @接收时间,
            @让步放行数量
        );
    END
END
GO
/****** Object:  StoredProcedure [dbo].[MES_QulityInspection_NGPart_FlowNode_Update]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[MES_QulityInspection_NGPart_FlowNode_Update]
    @FlowAID INT,
    @FlowNodeID INT,
    @让步放行数量 INT = NULL,
    @处理意见 NVARCHAR(2000) = NULL
AS
BEGIN
    SET NOCOUNT ON;
    Declare @接收时间 DATETIME = GETDATE();

    -- 检查FlowAID是否已存在（主键冲突）
    BEGIN
        -- 如果不存在则插入新记录
        UPDATE [dbo].[YL_质量检验_不合格品处理_处理节点] SET
		[让步放行数量]=@让步放行数量,
		[处理意见]=@处理意见,
		[完成时间]=GETDATE()
		WHERE [FlowAID]=@FlowAID AND [FlowNodeID]=@FlowNodeID
    END
END
GO
/****** Object:  StoredProcedure [dbo].[MES_QulityInspection_ProcessCheck]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[MES_QulityInspection_ProcessCheck]
	@TaskAID int=-1,
	@checkCount int=-1,
	@ngCount int=-1,
	@chkDescription nvarchar(50)='',
	@checker nvarchar(50)=''
AS
declare @OKCount int =@checkCount-@ngCount;

if(@checkCount>0 and @ngCount>=0 and @OKCount>=0)
BEGIN
	--更新任务的质检数据
	update MES_接口_生产计划_生产任务 set [不合格数量]=isnull([不合格数量],0)+@ngCount,[序检]=1 where AID=@TaskAID

	--保存巡检记录
	INSERT INTO [dbo].[YL_质量检验_质检记录]([TaskAID],[质检类型],[检验数量],[不合格数],[检测说明],[检测人],[检测时间])
    VALUES(@TaskAID,'序检',@checkCount,@ngCount,@chkDescription,@checker,getdate())
	
	 -- select '@TaskAID:'+@TaskAID+'@ngCount:'+@ngCount;

END

GO
/****** Object:  StoredProcedure [dbo].[MES_QulityInspection_ReceiveCheck]    Script Date: 2026/5/18 8:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- 创建存储过程 MES_QulityInspection_ReceiveCheck
CREATE PROCEDURE [dbo].[MES_QulityInspection_ReceiveCheck]
    @TaskAID bigint,
	@检测类型编号 int,
    @质检类型 NVARCHAR(50),
    @零件名称 NVARCHAR(200),
    @内部合同号 int,
    @零件编码 NVARCHAR(200),
    @计划号 int,
    @工序名称 NVARCHAR(100),
    @检测数量 INT,
    @合格数 INT,
    @不合格数 INT,
    @检测人 NVARCHAR(50),
    @检测时间 DATETIME,
    @计划生产数 INT,
    @检测说明 NVARCHAR(MAX)
AS
BEGIN
    SET NOCOUNT ON;

    BEGIN TRY
        BEGIN TRANSACTION;
		-- 获取当前任务的分配数量（指派数量）
		DECLARE @分配数量 INT
		SELECT @分配数量 = ISNULL(指派数量, 0) 
		FROM [dbo].[MES_接口_生产计划_生产任务] 
		WHERE AID = @TaskAID
		
		-- 获取当前任务已检验的总数量（包括本次）
		DECLARE @已检验总数 INT
		SELECT @已检验总数 = ISNULL(SUM(qc.检验数量), 0) 
		FROM [YL_MESDB].[dbo].[YL_质量检验_质检记录] qc
		WHERE qc.TaskAID = @TaskAID
		
		-- 计算本次检验后累计检验数量
		DECLARE @累计检验数量 INT = @已检验总数 + @检测数量
		
		-- 判断检验数量是否超过计划生产数
		IF @累计检验数量 > @计划生产数
		BEGIN
			ROLLBACK TRANSACTION;
			SELECT '0' AS result, 
				   '操作失败: 检验数量(' + CAST(@累计检验数量 AS NVARCHAR(10)) + 
				   ')超过计划生产数(' + CAST(@计划生产数 AS NVARCHAR(10)) + ')' AS message,
				   0 AS 总合格数,
				   0 AS 下一道工序AID,
				   0 AS 清零任务数
			RETURN
		END
        -- 插入新记录
        INSERT INTO [YL_MESDB].[dbo].[YL_质量检验_质检记录] (
            [TaskAID],
			[检测类型编号],
            [质检类型],
            [零件名称],
            [内部合同号],
            [零件编码],
            [计划号],
            [工序名称],
            [检验数量],
            [合格数],
            [不合格数],
            [检测人],
            [检测时间],
            [计划生产数],
            [检测说明]
        )
        VALUES (
            @TaskAID,
			@检测类型编号,
            @质检类型,
            @零件名称,
            @内部合同号,
            @零件编码,
            @计划号,
            @工序名称,
            @检测数量,
            @合格数,
            @不合格数,
            @检测人,
            @检测时间,
            @计划生产数,
            @检测说明
        )

        -- 获取当前任务的订单行号
        DECLARE @当前订单行号 INT
        SELECT @当前订单行号 = ISNULL(订单行号, 0) 
        FROM [dbo].[MES_接口_生产计划_生产任务] 
        WHERE AID = @TaskAID

    --    -- 计算同一订单号且同一订单行号的所有收检任务的合格数总和
    --    DECLARE @总合格数 INT
    --    SELECT @总合格数 = ISNULL(SUM(qc.合格数), 0) 
    --    FROM [YL_MESDB].[dbo].[YL_质量检验_质检记录] qc
    --    INNER JOIN [dbo].[MES_接口_生产计划_生产任务] task ON qc.TaskAID = task.AID
    --    WHERE task.订单编号 = @计划号 
    --      AND task.订单行号 = @当前订单行号
		  --AND qc.质检类型 = '收检'
        -- 查找下一道工序：同一个订单号、订单行号+1、拆分内码=1的任务
		DECLARE @总检测数 INT
        SELECT @总检测数 = ISNULL(SUM(qc.检验数量), 0) 
        FROM [YL_MESDB].[dbo].[YL_质量检验_质检记录] qc
        INNER JOIN [dbo].[MES_接口_生产计划_生产任务] task ON qc.TaskAID = task.AID
        WHERE task.订单编号 = @计划号 
          AND task.订单行号 = @当前订单行号
		  AND qc.质检类型 = '收检'
		if (@总检测数 = @计划生产数)
		begin
			UPDATE [dbo].[MES_接口_生产计划_生产任务] 
			SET 任务状态 = 4
			WHERE AID = @TaskAID
		end
        DECLARE @下一道工序AID INT
        SELECT @下一道工序AID = AID 
        FROM [dbo].[MES_接口_生产计划_生产任务] 
        WHERE 订单编号 = @计划号 
          AND 订单行号 = @当前订单行号 + 1 
          AND ISNULL(订单拆分内码, 1) = 1

        ---- 查找下一道工序中拆分内码>1的所有任务
        --DECLARE @拆分内码大于1的任务数 INT

        ---- 更新拆分内码>1的任务，指派数量设置为0
        --UPDATE [dbo].[MES_接口_生产计划_生产任务] 
        --SET 任务状态 = 1
        --WHERE 订单编号 = @计划号 
        --  AND 订单行号 = @当前订单行号 + 1 
        --  AND ISNULL(订单拆分内码, 0) > 1

        --SELECT @拆分内码大于1的任务数 = @@ROWCOUNT

        -- 如果找到下一道工序（拆分内码=1），则更新其指派数量为总合格数
        IF @下一道工序AID IS NOT NULL and @合格数 > 0
        BEGIN
            UPDATE [dbo].[MES_接口_生产计划_生产任务] 
            SET 任务状态 = 1
            WHERE AID = @下一道工序AID and  isnull(任务状态,0) < 1 
        END

        COMMIT TRANSACTION;

        ---- 返回操作结果
        SELECT '1' AS result, 
               '操作成功' AS message
        --       @总合格数 AS 总合格数,
        --       ISNULL(@下一道工序AID, 0) AS 下一道工序AID,
        --       @拆分内码大于1的任务数 AS 清零任务数

    END TRY
    BEGIN CATCH
        IF @@TRANCOUNT > 0
            ROLLBACK TRANSACTION;
        
        -- 返回错误信息
        SELECT '0' AS result, 
               '操作失败: ' + ERROR_MESSAGE() AS message,
               0 AS 总合格数,
               0 AS 下一道工序AID,
               0 AS 清零任务数
    END CATCH
END
GO
/****** Object:  StoredProcedure [dbo].[MES_QulityInspection_RoundCheck]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[MES_QulityInspection_RoundCheck]
	@TaskAID int=-1,
	@checkCount int=-1,
	@ngCount int=-1,
	@chkDescription nvarchar(500)='',
	@checker nvarchar(50)=''
AS
declare @OKCount int =@checkCount-@ngCount;

if(@checkCount>0 and @ngCount>=0 and @OKCount>=0)
BEGIN
	--更新任务的质检数据
	update MES_接口_生产计划_生产任务 set [不合格数量]=isnull([不合格数量],0)+@ngCount,[巡检]=1 where AID=@TaskAID
	--保存巡检记录
	INSERT INTO [dbo].[YL_质量检验_质检记录]([TaskAID],[质检类型],[检验数量],[不合格数],[检测说明],[检测人],[检测时间])
    VALUES(@TaskAID,'巡检',@checkCount,@ngCount,@chkDescription,@checker,getdate())

END

GO
/****** Object:  StoredProcedure [dbo].[MES_操作记录_获取任务暂停状态]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
-- 按任务获取暂停状态
CREATE PROCEDURE [dbo].[MES_操作记录_获取任务暂停状态]
    @TaskAID INT
AS
BEGIN
    SET NOCOUNT ON;
    
    BEGIN TRY
        -- 查询指定任务的最新暂停记录
        SELECT TOP 1
            p.TaskAID,
            p.关联操作类型 AS PreviousState,
            p.操作人 AS Operator,
            p.开始时间 AS PauseTime
        FROM [YL_加工中心_操作记录表] p
        WHERE p.操作类别 = '暂停'
          AND p.TaskAID = @TaskAID
          AND (p.结束时间 IS NULL OR p.结束时间 = '')  -- 还没有结束的暂停
          AND p.关联操作类型 IS NOT NULL
        ORDER BY p.开始时间 DESC
        
    END TRY
    BEGIN CATCH
        SELECT 
            NULL AS TaskAID,
            NULL AS PreviousState,
            NULL AS Operator,
            NULL AS PauseTime
        WHERE 1 = 0;
    END CATCH
END
GO
/****** Object:  StoredProcedure [dbo].[MES_操作记录_获取暂停状态]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
-- 保存暂停状态存储过程
CREATE PROCEDURE [dbo].[MES_操作记录_获取暂停状态]
    @操作人 NVARCHAR(50) = NULL
AS
BEGIN
    SET NOCOUNT ON;
    
    BEGIN TRY
        -- 查询最近的暂停记录（24小时内），且没有对应恢复操作的记录
        SELECT 
            p.TaskAID,
            p.关联操作类型 AS PreviousState,
            p.操作人 AS Operator,
            p.开始时间 AS PauseTime
        FROM [YL_加工中心_操作记录表] p
        WHERE p.操作类别 = '暂停'
          AND (p.结束时间 IS NULL OR p.结束时间 = '')  -- 还没有结束的暂停
          AND p.关联操作类型 IS NOT NULL
        ORDER BY p.开始时间 DESC
        
    END TRY
    BEGIN CATCH
        -- 返回空结果集
        SELECT 
            NULL AS TaskAID,
            NULL AS PreviousState,
            NULL AS Operator,
            NULL AS PauseTime
        WHERE 1 = 0;
    END CATCH
END

GO
/****** Object:  StoredProcedure [dbo].[MES_登录_班次信息]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:		<Author,,李显>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[MES_登录_班次信息]

AS
BEGIN
SELECT 词条编号 as [班次代码],词条名称 as [班次描述] FROM [dbo].[YL_基础表_数据字典] where [数据类别]='班次' ORDER BY 词条编号 
END
GO
/****** Object:  StoredProcedure [dbo].[MES_登录_工号密码验证]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO



CREATE PROCEDURE [dbo].[MES_登录_工号密码验证] 
@用户名 nvarchar(50) = '0001',
@密码 nvarchar(50) = '0001',
@工位号 nvarchar(50) = 'J07ET030'
AS
declare @Count int
select @Count = count(1) from  [dbo].基础表_用户角色 where [登录账号]=@用户名 and [登录密码]=@密码 

if @Count is null or @Count = 0
begin
	select '工号或密码错误，请重试！' as msg,0 as result
	return
end
else select * from 基础表_用户角色 where [登录账号]=@用户名 and [登录密码]=@密码 
-- 判断是否有该工位的权限  如果没有则反回相应消息提示
--declare @是否拥有权限 int
--declare @sql nvarchar(max)
--set @sql = 'select * from 人事档案管理_人员名单_视图 WHERE 考勤编号 = ' + ''''+@用户名+''''
--print @sql
--exec (@sql)
--print @是否拥有权限


--最后一步返回数据
--select top 1 * from  [dbo].[人事档案管理_人员名单]
--where 考勤编号=@用户名 and 密码=@密码 

GO
/****** Object:  StoredProcedure [dbo].[MES_登录_工位与名称_查询]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[MES_登录_工位与名称_查询]

AS
BEGIN
SELECT [VisCode] as 工位代码
      ,[VisCode] as MesWebCode
      ,[VisCode] as 工位号
      ,[Name] as 指南工位号
	  ,[Name] as 工位名称
  FROM [View_基础数据_工位]
  order by [VisCode]
END
GO
/****** Object:  StoredProcedure [dbo].[MES_接口_生产计划_Insert]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE PROCEDURE [dbo].[MES_接口_生产计划_Insert]
@订单编号 int = 0,
@合同号 nvarchar(100) = '',
@订单类型 nvarchar(100) = '',
@订单状态 nvarchar(100) = '',
@物料编号 nvarchar(100) = '',
@物料描述 nvarchar(100) = '',
@计划数量 int = 0,
@计量单位 nvarchar(100) = '',
@下达日期 datetime = null,
@计划开始 datetime = null,
@计划完成 datetime = null,
@项目代码 nvarchar(100) = '',
@同步时间 datetime = null,
@自制件属性 nvarchar(100) = '',
@预计齐套时间 datetime = null,
@备注 nvarchar(100) = '',
@计划号 nvarchar(100) = ''


as

DECLARE @CreateTime datetime = getdate()
DECLARE @标准工艺 int = 0
-- [订单编号],[合同号],[订单类型],[订单状态],[物料编号],[物料描述],[计划数量],[计量单位],[下达日期],[计划开始],[计划完成],[项目代码],[同步时间],[自制件属性]

IF (SELECT COUNT(1) FROM [MES_接口_生产计划] WHERE [订单编号] = @订单编号) > 0 BEGIN

UPDATE [MES_接口_生产计划] SET 
[合同号]   = @合同号,
[计划号]   = @计划号
--,[订单类型] = @订单类型
--,[订单状态] = @订单状态
--,[物料编号] = @物料编号
--,[物料描述] = @物料描述
--,[计划数量] = @计划数量
--,[计量单位] = @计量单位
--,[下达日期] = @下达日期
--预计齐套时间 = @预计齐套时间
--,[计划完成] = @计划完成
--,[项目代码] = @项目代码
--,[同步时间] = @同步时间
--[自制件属性] = @自制件属性
WHERE [订单编号] = @订单编号
--UPDATE [dbo].[MES_接口_生产计划_生产任务] SET [计划开始时间] = @预计齐套时间  WHERE [订单编号] = @订单编号
END ELSE BEGIN
select @标准工艺 = 标准工艺 from [MES_接口_生产计划] where 物料编号 = @物料编号
INSERT INTO [MES_接口_生产计划]([计划号],[订单编号],[合同号],[订单类型],[订单状态],[物料编号],[物料描述],[计划数量],[计量单位],[下达日期],[计划开始],[计划完成],[项目代码],[同步时间],[自制件属性],预计齐套时间,备注)
VALUES(@计划号,@订单编号,@合同号,@订单类型,@订单状态,@物料编号,@物料描述,@计划数量,@计量单位,@下达日期,@计划开始,@计划完成,@项目代码,@同步时间,@自制件属性,@预计齐套时间,@备注)

update [MES_接口_生产计划] set 标准工艺 = @标准工艺  where 物料编号 = @物料编号
IF (@自制件属性 like '%装配%')
BEGIN
    DECLARE @selectStr2 NVARCHAR(MAX)
	DECLARE @计划完成Str NVARCHAR(50)
    IF @计划完成 IS NOT NULL
        SET @计划完成Str = CONVERT(NVARCHAR(50), @计划完成, 120) -- yyyy-mm-dd hh:mi:ss格式
    ELSE
        SET @计划完成Str = 'NULL'
    SET @selectStr2 = N'
    INSERT INTO [dbo].[MES_接口_生产计划_生产任务] (
        不装配, 订单编号, 计划数量, 物料编码, 订单行号,
        顺序编号, 工序名称, 物料名称, 订单发货类型, 物料类型, 
        基本数量, 已发货数量, 订单拆分内码, 阶段标识, 可视订单,
        计划开始时间, 计划完成时间, 指派对象
    ) 
    SELECT 
        ''3'' as 不装配,
        ' + QUOTENAME(@订单编号, '''') + N' as 订单编号,
        ' + QUOTENAME(@计划数量, '''') + N' as 计划数量,
        '''+ @物料编号 + ''' as 物料编码,
        1 as 订单行号,
        1 as 顺序编号,
        ''装配'' as 工序名称,
        ''' + @物料描述 + ''' as 物料名称,
        ''im_Manual'' as 订单发货类型,
        ''pit_Resource'' as 物料类型,
        0 as 基本数量,
        0 as 已发货数量,
        1 as 订单拆分内码,
        -1 as 阶段标识,
        1 as 可视订单,
        NULL as 计划开始时间,
       ' + CASE WHEN @计划完成 IS NOT NULL 
                THEN '''' + @计划完成Str + '''' 
                ELSE 'NULL' 
           END + N' as 计划完成时间,
        ''' + @自制件属性 + ''' as 指派对象
    '
    
    PRINT @selectStr2
    EXEC sp_executesql @selectStr2

END

END


GO
/****** Object:  StoredProcedure [dbo].[MES_人员工时记录_获取进行中任务]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[MES_人员工时记录_获取进行中任务]
    @用户ID NVARCHAR(50)
AS
BEGIN
    SET NOCOUNT ON;
    
    BEGIN TRY
        -- 简化版本，只查询必要的字段
        SELECT 
            t.AID AS 操作记录ID,
            t.TaskAID,
            t.操作人 AS UserName,
            t.开始时间 AS StartTime,
            t.操作类别,
            t.操作类别编号,
            t.工序名称,
            t.工位名称,
            t.订单编号,
            t.物料编号,
            t.物料描述,
            t.阶段标识,
            -- 从生产任务表获取信息
            pt.订单编号 AS 生产订单编号,
            pt.物料编码 AS 零件编码,
            pt.物料名称 AS 零件名称,
            pt.工序名称 AS 任务工序名称,
            pt.指派对象,
            pt.任务状态,
            pt.指派数量 AS 分配数,
            pt.完成数量,
            pt.计划开始时间 AS 计划开始,
            pt.计划完成时间 AS 计划完成,
            pt.顺序编号 AS 阶段标识编号
        FROM [dbo].[YL_加工中心_操作记录表] t
        LEFT JOIN [dbo].[MES_接口_生产计划_生产任务] pt ON t.TaskAID = pt.AID
        WHERE t.操作人 = @用户ID
            AND t.操作类别 = '开始加工'
            AND t.结束时间 IS NULL
			and t.工位名称 like '%装配%'
			and t.操作数值 is not null
        ORDER BY t.开始时间 DESC;
        
        -- 返回状态信息
        SELECT '1' AS result, '查询成功' AS message;
        
    END TRY
    BEGIN CATCH
        DECLARE @ErrorMessage NVARCHAR(4000);
        SELECT @ErrorMessage = ERROR_MESSAGE();
        
        SELECT '0' AS result, '查询失败: ' + @ErrorMessage AS message;
        
        RAISERROR (@ErrorMessage, 16, 1);
    END CATCH
END
GO
/****** Object:  StoredProcedure [dbo].[MES_人员工时记录_获取进行中任务2]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[MES_人员工时记录_获取进行中任务2]
    @用户ID NVARCHAR(50)
AS
BEGIN
    SET NOCOUNT ON;
    
    BEGIN TRY
        -- 简化版本，只查询必要的字段
        SELECT 
            t.AID AS 操作记录ID,
            t.TaskAID,
            t.操作人 AS UserName,
            t.开始时间 AS StartTime,
            t.操作类别,
            t.操作类别编号,
            t.工序名称,
            t.工位名称,
            t.订单编号,
            t.物料编号,
            t.物料描述,
            t.阶段标识,
            -- 从生产任务表获取信息
            pt.订单编号 AS 生产订单编号,
            pt.物料编码 AS 零件编码,
            pt.物料名称 AS 零件名称,
            pt.工序名称 AS 任务工序名称,
            pt.指派对象,
            pt.任务状态,
            pt.指派数量 AS 分配数,
            pt.完成数量,
            pt.计划开始时间 AS 计划开始,
            pt.计划完成时间 AS 计划完成,
            pt.顺序编号 AS 阶段标识编号
        FROM [dbo].[YL_加工中心_操作记录表] t
        LEFT JOIN [dbo].[MES_接口_生产计划_生产任务] pt ON t.TaskAID = pt.AID
        WHERE 
             t.操作类别 = '开始加工'
            AND t.结束时间 IS NULL
			and t.工位名称 like '%装配%'
			and t.操作数值 is not null
        ORDER BY t.开始时间 DESC;
        
        -- 返回状态信息
        SELECT '1' AS result, '查询成功' AS message;
        
    END TRY
    BEGIN CATCH
        DECLARE @ErrorMessage NVARCHAR(4000);
        SELECT @ErrorMessage = ERROR_MESSAGE();
        
        SELECT '0' AS result, '查询失败: ' + @ErrorMessage AS message;
        
        RAISERROR (@ErrorMessage, 16, 1);
    END CATCH
END
GO
/****** Object:  StoredProcedure [dbo].[MES_人员工时记录_检查是否存在]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[MES_人员工时记录_检查是否存在]
    @TaskAID INT,
    @用户名 NVARCHAR(50)
AS
BEGIN
    SET NOCOUNT ON;
    
    BEGIN TRY
        -- 检查是否已经存在未结束的开始记录
        IF EXISTS (
            SELECT 1 FROM YL_加工中心_操作记录表 
            WHERE TaskAID = @TaskAID 
            AND 操作人 = @用户名 
            AND 操作类别 = '开始加工' 
            AND 结束时间 IS NULL
        )
        BEGIN
            SELECT '1' AS result, '已存在未结束的开始记录' AS message,
                   (SELECT TOP 1 开始时间 FROM YL_加工中心_操作记录表 
                    WHERE TaskAID = @TaskAID 
                    AND 操作人 = @用户名 
                    AND 操作类别 = '开始加工' 
                    AND 结束时间 IS NULL
                    ORDER BY 开始时间 DESC) AS 开始时间
        END
        ELSE
        BEGIN
            SELECT '0' AS result, '不存在未结束的开始记录' AS message
        END
    END TRY
    BEGIN CATCH
        SELECT '0' AS result, '检查失败: ' + ERROR_MESSAGE() AS message
    END CATCH
END
GO
/****** Object:  StoredProcedure [dbo].[MES_人员工时记录_结束]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[MES_人员工时记录_结束]
    @TaskAID INT,
    @用户ID NVARCHAR(50),
    @用户名 NVARCHAR(50),
    @操作人 NVARCHAR(50),
    @备注 NVARCHAR(200) = '',
    @工序说明 NVARCHAR(200) = '',
    @异常说明 NVARCHAR(200) = '',
    @本次检数 NVARCHAR(200) = 0,
    -- ========== 加班相关参数 ==========
    @是否加班 INT = 0,                           -- 是否加班（1=是，0=否）
    @加班人员 NVARCHAR(500) = NULL,              -- 普通加班人员（逗号分隔）
    @特殊加班人员 NVARCHAR(500) = NULL,          -- 特殊加班人员（逗号分隔）
    @是否休息日 INT = 0,                         -- 是否休息日（1=是，0=否）
    @是否法定休息日 INT = 0,                     -- 是否法定休息日（1=是，0=否）
    @班次标准工时 NVARCHAR = 8                        -- 班次标准工时（分钟），默认8小时
AS
BEGIN
    BEGIN TRY
        -- 从任务表获取相关信息
        DECLARE @订单编号 NVARCHAR(100),
                @物料编号 NVARCHAR(100),
                @物料描述 NVARCHAR(200),
                @工序名称 NVARCHAR(100),
                @工位名称 NVARCHAR(100),
                @阶段标识 INT,
                @检验数 INT
        
        DECLARE @结束时间 DATETIME = GETDATE()
        
        SELECT 
            @订单编号 = ISNULL(订单编号, ''),
            @物料编号 = ISNULL(物料编码, ''),
            @物料描述 = ISNULL(物料名称, ''),
            @工序名称 = ISNULL(工序名称, ''),
            @工位名称 = ISNULL(指派对象, ''),
            @阶段标识 = ISNULL(顺序编号, -1),
            @检验数 = ISNULL(本次检数, 0)
        FROM [dbo].[MES_接口_生产计划_生产任务]
        WHERE AID = @TaskAID
        
        -- 更新本次检数数量
        UPDATE [dbo].[MES_接口_生产计划_生产任务] 
        SET 本次检数 = ISNULL(@检验数, 0) + ISNULL(@本次检数, 0) 
        WHERE AID = @TaskAID
        
        -- 查找对应的开始记录
        DECLARE @开始记录ID INT,
                @开始时间 DATETIME
        
        SELECT TOP 1 
            @开始记录ID = AID,
            @开始时间 = 开始时间
        FROM YL_加工中心_操作记录表 
        WHERE TaskAID = @TaskAID 
            AND 操作人 = @用户名 
            AND 操作类别 = '开始加工' 
            AND 结束时间 IS NULL
        ORDER BY 开始时间 DESC
        
        IF @开始记录ID IS NULL
        BEGIN
            SELECT '0' AS result, '未找到对应的开始记录' AS message
            RETURN
        END
        
        -- ========== 获取白班结束时间 ==========
        DECLARE @白班结束时间 TIME
        DECLARE @白班结束时间_完整 DATETIME
        
        SELECT @白班结束时间 = 结束时间
        FROM [班次表]
        WHERE 班次名称 = '白班'
        
        IF @白班结束时间 IS NULL
        BEGIN
            SET @白班结束时间 = '16:30:00'
        END
        
        SET @白班结束时间_完整 = CAST(CAST(@结束时间 AS DATE) AS DATETIME) + CAST(@白班结束时间 AS DATETIME)
        
        -- ========== 计算工作时间和加班时间 ==========
        DECLARE @总工时 INT = DATEDIFF(SECOND, @开始时间, @结束时间)
        DECLARE @工作时间 INT = 0
        DECLARE @加班时长秒 INT = 0
        DECLARE @加班开始时间 DATETIME = NULL
        DECLARE @报工开始时间 DATETIME = NULL
        DECLARE @报工结束时间 DATETIME = NULL
        
        -- 休息日或法定休息日
        IF @是否休息日 = 1 OR @是否法定休息日 = 1
        BEGIN
            IF @是否加班 = 1
            BEGIN
                -- 休息日/法定休息日 + 选择加班：全部算加班，没有报工
                SET @加班时长秒 = @总工时
                SET @加班开始时间 = @开始时间
                SET @工作时间 = 0
            END
            ELSE
            BEGIN
                -- 休息日/法定休息日 + 选择不加班：全部算报工
                SET @工作时间 = @总工时
                SET @报工开始时间 = @开始时间
                SET @报工结束时间 = @结束时间
                SET @加班时长秒 = 0
                SET @加班开始时间 = NULL
            END
        END
        ELSE
        BEGIN
            -- 工作日
            IF @是否加班 = 1
            BEGIN
                -- 工作日 + 选择加班
                IF @开始时间 < @白班结束时间_完整
                BEGIN
                    -- 开始时间在白班结束时间之前
                    -- 报工时间 = 白班结束时间 - 开始时间
                    SET @工作时间 = DATEDIFF(SECOND, @开始时间, @白班结束时间_完整)
                    SET @报工开始时间 = @开始时间
                    SET @报工结束时间 = @白班结束时间_完整
                    
                    -- 加班时间 = 结束时间 - 白班结束时间
                    IF @结束时间 > @白班结束时间_完整
                    BEGIN
                        SET @加班时长秒 = DATEDIFF(SECOND, @白班结束时间_完整, @结束时间)
                        SET @加班开始时间 = @白班结束时间_完整
                    END
                END
                ELSE
                BEGIN
                    -- 开始时间在白班结束时间之后
                    -- 没有报工时间
                    SET @工作时间 = 0
                    -- 加班时间 = 结束时间 - 开始时间
                    SET @加班时长秒 = @总工时
                    SET @加班开始时间 = @开始时间
                END
            END
            ELSE
            BEGIN
                -- 工作日 + 选择不加班：全部算报工
                SET @工作时间 = @总工时
                SET @报工开始时间 = @开始时间
                SET @报工结束时间 = @结束时间
                SET @加班时长秒 = 0
                SET @加班开始时间 = NULL
            END
        END
        
        -- 更新开始记录的结束时间和工时信息
        UPDATE YL_加工中心_操作记录表 
        SET 
            结束时间 = @结束时间,
            工时 = @总工时,
            总时长 = @总工时,
            最后编辑人 = @操作人,
            最后编辑时间 = GETDATE(),
            操作数值 = @总工时,
            操作描述 = '用户 ' + @用户名 + ' 结束加工，' +
                        '开始时间：' + CONVERT(NVARCHAR(19), @开始时间, 120) + '，' +
                        '结束时间：' + CONVERT(NVARCHAR(19), @结束时间, 120) + '，' +
                        '工作时间：' + CAST(@总工时 AS NVARCHAR(10)) + ' 秒' +
                        CASE WHEN @加班时长秒 > 0 THEN '，加班时间：' + CAST(@加班时长秒 AS NVARCHAR(10)) + ' 秒' ELSE '' END,
            备注 = @备注,
            工序说明 = @工序说明,
            异常说明 = @异常说明
        WHERE AID = @开始记录ID
        IF @是否休息日 = 1 OR @是否法定休息日 = 1
		BEGIN
			UPDATE YL_加工中心_操作记录表 
			SET 
				结束时间 = @结束时间,
				工时 = 0,
				总时长 = 0,
				最后编辑人 = @操作人,
				最后编辑时间 = GETDATE(),
				操作数值 = 0,
				操作描述 = '用户 ' + @用户名 + ' 结束加工，' +
							'开始时间：' + CONVERT(NVARCHAR(19), @开始时间, 120) + '，' +
							'结束时间：' + CONVERT(NVARCHAR(19), @结束时间, 120) + '，' +
							'工作时间：' + CAST(@总工时 AS NVARCHAR(10)) + ' 秒' +
							CASE WHEN @加班时长秒 > 0 THEN '，加班时间：' + CAST(@加班时长秒 AS NVARCHAR(10)) + ' 秒' ELSE '' END,
				备注 = @备注,
				工序说明 = @工序说明,
				异常说明 = @异常说明
			WHERE AID = @开始记录ID
		end
        -- ========== 保存报工记录 ==========
        IF @工作时间 > 0
        BEGIN
            DECLARE @报工类型 NVARCHAR(50)
            
            IF @是否法定休息日 = 1 AND @是否加班 = 0
            BEGIN
                SET @报工类型 = '法定休息日工作'
            END
            ELSE IF @是否休息日 = 1 AND @是否加班 = 0
            BEGIN
                SET @报工类型 = '休息日工作'
            END
            ELSE
            BEGIN
                SET @报工类型 = '报工'
            END
            
            INSERT INTO [dbo].[YL_加工中心_报工记录]
                ([报工日期],[班次],[工位编号],[工位名称],[操作人],[工时类型],[报工数量],[工时],[报工说明],[订单编号],[TaskAID],[TaskAID_Binding],[报工时间])
            VALUES
                ('', '装配', '', @工位名称, @操作人, @报工类型, 0, @工作时间, '', @订单编号, @TaskAID, '', GETDATE())
        END
        
        -- ========== 加班记录处理 ==========
        IF @是否加班 = 1 AND @加班时长秒 > 0 AND (@加班人员 IS NOT NULL OR @特殊加班人员 IS NOT NULL)
        BEGIN
            -- 创建临时表存储所有加班人员
            CREATE TABLE #TempOvertimePersons (人员名称 NVARCHAR(50), 是否特殊 BIT DEFAULT 0)
            
            -- 解析普通加班人员
            IF @加班人员 IS NOT NULL AND @加班人员 != ''
            BEGIN
                DECLARE @当前人员 NVARCHAR(50)
                DECLARE @位置 INT
                DECLARE @人员列表 NVARCHAR(500) = @加班人员
                
                WHILE LEN(@人员列表) > 0
                BEGIN
                    SET @位置 = CHARINDEX(',', @人员列表)
                    
                    IF @位置 > 0
                    BEGIN
                        SET @当前人员 = LTRIM(RTRIM(SUBSTRING(@人员列表, 1, @位置 - 1)))
                        SET @人员列表 = SUBSTRING(@人员列表, @位置 + 1, LEN(@人员列表))
                    END
                    ELSE
                    BEGIN
                        SET @当前人员 = LTRIM(RTRIM(@人员列表))
                        SET @人员列表 = ''
                    END
                    
                    IF LEN(@当前人员) > 0
                    BEGIN
                        INSERT INTO #TempOvertimePersons (人员名称, 是否特殊) VALUES (@当前人员, 0)
                    END
                END
            END
            
            -- 解析特殊加班人员
            IF @特殊加班人员 IS NOT NULL AND @特殊加班人员 != ''
            BEGIN
                SET @人员列表 = @特殊加班人员
                WHILE LEN(@人员列表) > 0
                BEGIN
                    SET @位置 = CHARINDEX(',', @人员列表)
                    
                    IF @位置 > 0
                    BEGIN
                        SET @当前人员 = LTRIM(RTRIM(SUBSTRING(@人员列表, 1, @位置 - 1)))
                        SET @人员列表 = SUBSTRING(@人员列表, @位置 + 1, LEN(@人员列表))
                    END
                    ELSE
                    BEGIN
                        SET @当前人员 = LTRIM(RTRIM(@人员列表))
                        SET @人员列表 = ''
                    END
                    
                    IF LEN(@当前人员) > 0
                    BEGIN
                        IF EXISTS (SELECT 1 FROM #TempOvertimePersons WHERE 人员名称 = @当前人员)
                        BEGIN
                            UPDATE #TempOvertimePersons SET 是否特殊 = 1 WHERE 人员名称 = @当前人员
                        END
                        ELSE
                        BEGIN
                            INSERT INTO #TempOvertimePersons (人员名称, 是否特殊) VALUES (@当前人员, 1)
                        END
                    END
                END
            END
            
            -- 根据加班类型确定词条编号和名称
            DECLARE @加班词条编号 INT
            DECLARE @加班词条名称 NVARCHAR(50)
            
            IF @是否法定休息日 = 1
            BEGIN
                SET @加班词条编号 = 11
                SET @加班词条名称 = '法定休息日加班'
            END
            ELSE IF @是否休息日 = 1
            BEGIN
                SET @加班词条编号 = 10
                SET @加班词条名称 = '休息日加班'
            END
            ELSE
            BEGIN
                SET @加班词条编号 = 8
                SET @加班词条名称 = '加班'
            END
            
            DECLARE @加班时长分钟显示 INT = CEILING(@加班时长秒 / 60.0)
            
            -- 插入加班记录
            INSERT INTO [dbo].[YL_加工中心_操作记录表] (
                操作类别编号,
                操作类别,
                阶段标识,
                工序名称,
                工位编号,
                操作人,
                订单编号,
                物料编号,
                物料描述,
                操作数值,
                操作内容,
                操作描述,
                开始时间,
                结束时间,
                总时长,
                报工日期,
                已报工,
                不装配,
                最后编辑人,
                最后编辑时间,
                TaskAID,
                工位名称,
                班次标准工时
            )
            SELECT 
                @加班词条编号,
                @加班词条名称,
                0,
                @工序名称,
                '',
                t.人员名称,
                @订单编号,
                @物料编号,
                @物料描述,
                0,
                '报工',
                CASE 
                    WHEN @是否法定休息日 = 1 AND @是否加班 = 1 THEN '法定休息日报工加班'
                    WHEN @是否法定休息日 = 1 AND @是否加班 = 0 THEN '法定休息日报工'
                    WHEN @是否休息日 = 1 AND @是否加班 = 1 THEN '休息日报工加班'
                    WHEN @是否休息日 = 1 AND @是否加班 = 0 THEN '休息日报工'
                    ELSE '工作日加班'
                END + 
                '，工作时间段：' + CONVERT(NVARCHAR(8), @加班开始时间, 108) + '-' + CONVERT(NVARCHAR(8), @结束时间, 108) +
                '，加班时长：' + CAST(@加班时长分钟显示 AS NVARCHAR) + '分钟（' + CAST(@加班时长秒 AS NVARCHAR) + '秒）' +
                CASE WHEN t.是否特殊 = 1 THEN '，特殊加班人员，班次标准工时：' + CAST(@班次标准工时 AS NVARCHAR) + '小时' ELSE '' END,
                @加班开始时间,
                @结束时间,
                @加班时长秒,
                CAST(@结束时间 AS DATE),
                1,
                '否',
                @操作人,
                GETDATE(),
                @TaskAID,
                @工位名称,
                CASE WHEN t.是否特殊 = 1 THEN @班次标准工时 ELSE 8 END
            FROM #TempOvertimePersons t
            
            DROP TABLE #TempOvertimePersons
        END
        
        SELECT '1' AS result, '结束记录成功' AS message, @工作时间 AS 工时秒数
        
    END TRY
    BEGIN CATCH
        SELECT '0' AS result, ERROR_MESSAGE() AS message
    END CATCH
END
GO
/****** Object:  StoredProcedure [dbo].[MES_人员工时记录_开始]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
-- 人员工时记录 - 开始操作
CREATE PROCEDURE [dbo].[MES_人员工时记录_开始]
    @TaskAID INT,
    @用户ID NVARCHAR(50),
    @用户名 NVARCHAR(50),
    @操作人 NVARCHAR(50)
AS
BEGIN
    BEGIN TRY
        -- 从任务表获取相关信息
        DECLARE @订单编号 NVARCHAR(100),
                @物料编号 NVARCHAR(100),
                @物料描述 NVARCHAR(200),
                @工序名称 NVARCHAR(100),
                @工位名称 NVARCHAR(100),
                @阶段标识 INT
        declare @任务状态 int=-1  --0待执行，1可执行，2已开工，4已完成。
        SELECT 
            @订单编号 = ISNULL(订单编号, ''),
            @物料编号 = ISNULL(物料编码, ''),
            @物料描述 = ISNULL(物料名称, ''),
            @工序名称 = ISNULL(工序名称, ''),
            @工位名称 = ISNULL(指派对象, ''),
            @阶段标识 = ISNULL(顺序编号, -1)
        FROM[dbo].[MES_接口_生产计划_生产任务]
        WHERE AID = @TaskAID
        
        -- 检查是否已经存在未结束的开始记录
        IF EXISTS (
            SELECT 1 FROM YL_加工中心_操作记录表 
            WHERE TaskAID = @TaskAID 
            AND 操作人 = @用户名 
            AND 操作类别 = '开始加工' 
            AND 结束时间 IS NULL
        )
        BEGIN
            SELECT '0' AS result, '该用户已有未结束的开始记录' AS message
            RETURN
        END
        
        -- 更新任务状态为已开工
		select @任务状态=isnull(任务状态,0)from View_生产订单_MES where TaskAID=@TaskAID
		if(@任务状态 = 1) --可执行任务
		begin
			UPDATE MES_接口_生产计划_生产任务
			SET 
				任务状态 = '2',
				最后编辑人 = @操作人,
				最后编辑时间 = GETDATE()
			WHERE AID = @TaskAID
		end
        -- 记录开始操作
        INSERT INTO YL_加工中心_操作记录表 (
            操作类别编号,
            操作类别,
            阶段标识,
            工序名称,
            工位名称,
            操作人,
            合同号,
            订单编号,
            物料编号,
            物料描述,
            操作数值,
            操作内容,
            操作描述,
            TaskAID,
            开始时间,
            最后编辑人,
            最后编辑时间,
            关联操作类型
        ) VALUES (
            4,  -- 操作类别编号：11表示人员开始
            '开始加工',
            @阶段标识,
            @工序名称,
            @工位名称,
            @用户名,
            '',  -- 合同号，可根据需要从相关表获取
            @订单编号,
            @物料编号,
            @物料描述,
            0,   -- 操作数值，开始时为0
            '开始加工',
            '用户 ' + @用户名 + ' 开始加工任务',
            @TaskAID,
            GETDATE(),
            @操作人,
            GETDATE(),
            '开始加工'
        )
        
        -- 获取插入的记录ID
        DECLARE @记录ID INT = SCOPE_IDENTITY()
        
        SELECT '1' AS result, '开始记录成功' AS message, @记录ID AS 记录ID
        
    END TRY
    BEGIN CATCH
        SELECT '0' AS result, ERROR_MESSAGE() AS message
    END CATCH
END
GO
/****** Object:  StoredProcedure [dbo].[p_PopFirstWord]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


Create PROCEDURE [dbo].[p_PopFirstWord]
    @SourceString   varchar(4000) = NULL OUTPUT,
    @FirstWord      varchar(4000) = NULL OUTPUT
AS
    SET NOCOUNT ON

    -- Procedure accepts a comma delimited string as the first parameter
    -- Procedure outputs the first word in the second parameter
    -- Procedure outputs the remainder of the delimeted string in the first parameter
    -- Procedure yields the length of the First Word as the return value

    DECLARE @Oldword        varchar(4000)
    DECLARE @Length         INT
    DECLARE @CommaLocation  INT

    SELECT @Oldword = @SourceString

    IF NOT @Oldword IS NULL
    BEGIN
        SELECT @CommaLocation = CHARINDEX(',',@Oldword)
        SELECT @Length = DATALENGTH(@Oldword)

        IF @CommaLocation = 0
        BEGIN
            SELECT @FirstWord = @Oldword
            SELECT @SourceString = NULL

            RETURN @Length
        END

        SELECT @FirstWord = SUBSTRING(@Oldword, 1, @CommaLocation -1)
        SELECT @SourceString = SUBSTRING(@Oldword, @CommaLocation + 1, @Length - @CommaLocation)

        RETURN @Length - @CommaLocation
    END

    RETURN 0



GO
/****** Object:  StoredProcedure [dbo].[Prog_MES_GetDictionar_ByType]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Prog_MES_GetDictionar_ByType]
	@数据类别 NVARCHAR(50)
AS
BEGIN
	SELECT [词条编号],[词条名称] FROM [YL_基础表_数据字典] where 数据类别=@数据类别 order by [词条编号]
END
GO
/****** Object:  StoredProcedure [dbo].[Prog_MES_GetProductOrder_byAID]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Prog_MES_GetProductOrder_byAID]
	@TaskAID bigint
AS
BEGIN
declare @订单编号 int=-1
declare @订单行号 int=-1
select @订单编号=[订单编号],@订单行号 = 订单行号 FROM [View_生产订单_MES] where TaskAID=@TaskAID
SELECT [订单编号]
      ,[合同号]
      ,[物料编号]
      ,[物料描述]
      ,[占用情况]
      ,[加急状态]
      ,[排产状态]
      ,[订单行号]
      ,[阶段标识]
      ,[工序名称]
      ,[顺序编号]
      ,[总工时]
      ,[不装配]
      ,[指派对象编号]
      ,[指派对象]
      ,ISNULL([指派数量],0) as [指派数量]
      ,[计划开始时间]
      ,[计划完成时间]
      ,[最晚开始时间]
      ,[派工状态]
      ,[派工时间]
      ,[任务状态]
      ,[修改时间]
      ,[外协通知]
      ,[优先级]
      ,[未完成说明]
      ,[派工特殊说明]
      ,[最后编辑人]
      ,[最后编辑时间]
      ,[订单拆分内码]
	  ,[计划数量]
      ,ISNULL([可执行],0) as [可执行]
      ,[收料]
      ,ISNULL([收料数量],0) as [收料数量]
      ,[开工]
      ,[首检]
      ,[巡检]
      ,ISNULL([完成数量],0) as [完成数量]
      ,[进度]
      ,[序检]
      ,[测试]
      ,[入库]
	  ,ISNULL([加工状态],0) as [加工状态]
      ,[TaskAID]
	  ,ISNULL((
          SELECT SUM(ISNULL(合格数, 0)) 
          FROM [dbo].[YL_质量检验_质检记录] qc
          INNER JOIN [View_生产订单_MES] vt ON qc.TaskAID = vt.TaskAID
          WHERE vt.[订单编号] = vo.[订单编号] 
            AND vt.[订单行号] = vo.[订单行号]-1
			AND qc.检测类型编号 = '6'
      ), 0) as [上序合格数]
  FROM [dbo].[View_生产订单_MES] vo
  WHERE [TaskAID]=@TaskAID
END
GO
/****** Object:  StoredProcedure [dbo].[Prog_MES_LoadProcess]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Prog_MES_LoadProcess]
AS
SELECT [工艺编号], [工序名称] FROM [基础表_工序] ORDER BY [工艺编号]
GO
/****** Object:  StoredProcedure [dbo].[Prog_MES_LoadStations]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Prog_MES_LoadStations] 
AS
BEGIN
	--SELECT [VisCode],[Name] as OPName FROM [MES_资源主数据] Where [Type]='rtMachine' order by VisCode
	SELECT [VisCode],[Name] as OPName FROM [MES_资源主数据] where type='rtMachine' AND Active='tYES' AND IssueMethod='rimManual' or Name='外协' order by VisCode
END
GO
/****** Object:  StoredProcedure [dbo].[sp_xt_pagesplit]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[sp_xt_pagesplit]
@tbname sysname,
@fieldkey sysname,
@where nvarchar(1000),
@fieldshow nvarchar(max),
@fieldOrder nvarchar(1000),
@PageCurrent int=1,
@PageSize int=30,
@PageCount int OUTPUT,
@ItemCount int output	
AS
BEGIN
    SET NOCOUNT ON
    
    -- 参数检查
    IF ISNULL(@PageCurrent,0)<1 SET @PageCurrent=1
    IF ISNULL(@PageSize,0)<1 SET @PageSize=10
    IF ISNULL(@FieldShow,N'')=N'' SET @FieldShow=N'*'
    
    -- 处理排序
    DECLARE @OrderBy nvarchar(1000)
    IF ISNULL(@FieldOrder,N'')=N''
        SET @OrderBy = N''
    ELSE
        SET @OrderBy = N'ORDER BY ' + LTRIM(@FieldOrder)
    
    -- 处理条件 - 重要：去掉WHERE关键字，只保留条件内容
    DECLARE @WhereCondition nvarchar(1000)
    IF ISNULL(@Where,N'')=N''
        SET @WhereCondition = N''
    ELSE
        SET @WhereCondition = @Where  -- 只保存条件内容，不加WHERE
    
    -- 清理字段名
    SET @fieldkey = LTRIM(RTRIM(@fieldkey))
    DECLARE @quotedKey NVARCHAR(128) = QUOTENAME(@fieldkey)
    
    -- 计算总记录数
    DECLARE @sql nvarchar(MAX)
    IF @WhereCondition = N''
        SET @sql = N'SELECT @ItemCount = COUNT(*) FROM ' + @tbname
    ELSE
        SET @sql = N'SELECT @ItemCount = COUNT(*) FROM ' + @tbname + N' WHERE ' + @WhereCondition
    
    EXEC sp_executesql @sql, N'@ItemCount int OUTPUT', @ItemCount OUTPUT
    
    -- 计算总页数
    SET @PageCount = CEILING((@ItemCount + 0.0) / @PageSize)
    IF @PageCount = 0 SET @PageCount = 1
    
    -- 返回当前页数据
    DECLARE @TopRows INT = (@PageCurrent - 1) * @PageSize
    
    IF @PageCurrent = 1
    BEGIN
        -- 第一页
        IF @WhereCondition = N''
            SET @sql = N'SELECT TOP ' + CONVERT(NVARCHAR, @PageSize) + N' ' + @FieldShow + N'
                        FROM ' + @tbname + N' ' + @OrderBy
        ELSE
            SET @sql = N'SELECT TOP ' + CONVERT(NVARCHAR, @PageSize) + N' ' + @FieldShow + N'
                        FROM ' + @tbname + N' WHERE ' + @WhereCondition + N' ' + @OrderBy
    END
    ELSE
    BEGIN
        -- 其他页
        IF @WhereCondition = N''
        BEGIN
            -- 无条件的情况
            SET @sql = N'SELECT TOP ' + CONVERT(NVARCHAR, @PageSize) + N' ' + @FieldShow + N'
                        FROM ' + @tbname + N'
                        WHERE ' + @quotedKey + N' NOT IN (
                            SELECT TOP ' + CONVERT(NVARCHAR, @TopRows) + N' ' + @quotedKey + N'
                            FROM ' + @tbname + N' ' + @OrderBy + N'
                        ) ' + @OrderBy
        END
        ELSE
        BEGIN
            -- 有条件的情况
            SET @sql = N'SELECT TOP ' + CONVERT(NVARCHAR, @PageSize) + N' ' + @FieldShow + N'
                        FROM ' + @tbname + N'
                        WHERE ' + @quotedKey + N' NOT IN (
                            SELECT TOP ' + CONVERT(NVARCHAR, @TopRows) + N' ' + @quotedKey + N'
                            FROM ' + @tbname + N' WHERE ' + @WhereCondition + N' ' + @OrderBy + N'
                        ) AND ' + @WhereCondition + N' ' + @OrderBy
        END
    END
    
    -- 调试用，可以注释掉
    -- PRINT @sql
    
    -- 执行
    EXEC(@sql)
END
GO
/****** Object:  StoredProcedure [dbo].[sp_xt_pagesplit_group]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*
分页存储过程；
创建： 20070123
*/
CREATE    PROCEDURE [dbo].[sp_xt_pagesplit_group]
@tbname		sysname, --要分页显示的表名
@fieldkey	sysname, --用于定位记录的主键(惟一键)字段,只能是单个字段
@where		nvarchar(1000),	--查询条件
@fieldshow	nvarchar(1000), --以逗号分隔的要显示的字段列表,如果不指定,则显示所有字段
@fieldOrder	nvarchar(1000), ----以逗号分隔的排序字段列表,可以指定在字段后面指定DESC/ASC  --用于指定排序顺序

@GroupBy nvarchar(1000) = null, -- 加分组20200225 ZDY
@PageCurrent 	int=1,          --要显示的页码
@PageSize   	int=30,         --每页的大小(记录数)
@PageCount  	int OUTPUT,     --总页数
@ItemCount	int output	--数据总数	
AS

DECLARE @sql nvarchar(4000)
SET NOCOUNT ON
--检查对象是否有效
IF OBJECT_ID(@tbname) IS NULL
BEGIN
RAISERROR(N'对象"%s"不存在',1,16,@tbname)
RETURN
END
IF OBJECTPROPERTY(OBJECT_ID(@tbname),N'IsTable')=0
AND OBJECTPROPERTY(OBJECT_ID(@tbname),N'IsView')=0
AND OBJECTPROPERTY(OBJECT_ID(@tbname),N'IsTableFunction')=0
BEGIN
RAISERROR(N'"%s"不是表、视图或者表值函数',1,16,@tbname)
RETURN
END

--分页字段检查
IF ISNULL(@FieldKey,N'')=''
BEGIN
RAISERROR(N'分页处理需要主键（或者惟一键）',1,16)
RETURN
END

--其他参数检查及规范
IF ISNULL(@PageCurrent,0)<1 SET @PageCurrent=1
IF ISNULL(@PageSize,0)<1 SET @PageSize=10
IF ISNULL(@FieldShow,N'')=N'' SET @FieldShow=N'*'
IF ISNULL(@FieldOrder,N'')=N''
SET @FieldOrder=N''
ELSE
SET @FieldOrder=N'ORDER BY '+LTRIM(@FieldOrder)
IF ISNULL(@Where,N'')=N''
SET @Where=N''
ELSE
SET @Where=N'WHERE ('+@Where+N')'

--如果@PageCount为NULL值,则计算总页数(这样设计可以只在第一次计算总页数,以后调用时,把总页数传回给存储过程,避免再次计算总页数,对于不想计算总页数的处理而言,可以给@PageCount赋值)
/*IF @PageCount IS NULL
BEGIN*/
if @GroupBy is not null -- 加分组20200225 ZDY
	begin
		SET @sql=N'SELECT @PageCount=COUNT(*) from ( SELECT COUNT(*) as q'
		+N' FROM '+@tbname
		+N' '+@Where
		+N' '+@GroupBy -- 加分组20200225 ZDY
		+N' ) as a'
	end
else
	begin
		SET @sql=N'SELECT @PageCount=COUNT(*)'
		+N' FROM '+@tbname
		+N' '+@Where
	end

EXEC sp_executesql @sql,N'@PageCount int OUTPUT',@PageCount OUTPUT
set @ItemCount = @PageCount
SET @PageCount=ceiling((@PageCount+@PageSize-1)/@PageSize)
if(@pagecount=0)
	set @pagecount=1
--END

--计算分页显示的TOPN值
DECLARE @TopN varchar(20),@TopN1 varchar(20)
SELECT @TopN=@PageSize,
@TopN1=@PageCurrent*@PageSize

print @topn1;

--第一页直接显示
IF @PageCurrent=1
	begin
		EXEC(N'SELECT TOP '+@TopN
		+N' '+@FieldShow
		+N' FROM '+@tbname
		+N' '+@Where
		+N' '+@GroupBy -- 加分组20200225 ZDY
		+N' '+@FieldOrder)
	end
ELSE
	BEGIN
		SELECT @PageCurrent=@TopN1,
		@sql=N' SELECT @n=@n-1,@s=CASE WHEN @n<'+@TopN
		+N' THEN @s+N'',''+QUOTENAME(RTRIM(CAST('+@FieldKey
		+N' as nvarchar(4000))),N'''''''') ELSE N'''' END FROM '+@tbname
		+N' '+@Where
		+N' '+@GroupBy -- 加分组20200225 ZDY
		+N' '+@FieldOrder
		SET ROWCOUNT @PageCurrent

		EXEC sp_executesql @sql,
		N'@n int,@s nvarchar(4000) OUTPUT',
		@PageCurrent,@sql OUTPUT

		SET ROWCOUNT 0
		IF @sql=N''
			begin
				EXEC(N'SELECT TOP 0'
				+N' '+@FieldShow
				+N' FROM '+@tbname)
			
			end
		ELSE
			BEGIN
				SET @sql=STUFF(@sql,1,1,N'')
				

				--执行查询
				EXEC(N'SELECT TOP '+@TopN
				+N' '+@FieldShow
				+N' FROM '+@tbname
				+N' WHERE '+@FieldKey
				+N' IN('+@sql
				+N') '
				+N' '+@GroupBy -- 加分组20200225 ZDY
				+N' '
				+@FieldOrder)
		
			END
	END
GO
/****** Object:  StoredProcedure [dbo].[sp_xt_pagesplit1]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO





/*
分页存储过程；
创建： 20070123
*/
CREATE    PROCEDURE [dbo].[sp_xt_pagesplit1]
@tbname		sysname, --要分页显示的表名
@fieldkey	sysname, --用于定位记录的主键(惟一键)字段,只能是单个字段
@where		nvarchar(1000),	--查询条件
@fieldshow	nvarchar(1000), --以逗号分隔的要显示的字段列表,如果不指定,则显示所有字段
@fieldOrder	nvarchar(1000), ----以逗号分隔的排序字段列表,可以指定在字段后面指定DESC/ASC  --用于指定排序顺序

@PageCurrent 	int=1,          --要显示的页码
@PageSize   	int=30,         --每页的大小(记录数)
@PageCount  	int OUTPUT,     --总页数
@ItemCount	int output	--数据总数	
AS

DECLARE @sql nvarchar(4000)
SET NOCOUNT ON
--检查对象是否有效
IF OBJECT_ID(@tbname) IS NULL
BEGIN
RAISERROR(N'对象"%s"不存在',1,16,@tbname)
RETURN
END
IF OBJECTPROPERTY(OBJECT_ID(@tbname),N'IsTable')=0
AND OBJECTPROPERTY(OBJECT_ID(@tbname),N'IsView')=0
AND OBJECTPROPERTY(OBJECT_ID(@tbname),N'IsTableFunction')=0
BEGIN
RAISERROR(N'"%s"不是表、视图或者表值函数',1,16,@tbname)
RETURN
END

--分页字段检查
IF ISNULL(@FieldKey,N'')=''
BEGIN
RAISERROR(N'分页处理需要主键（或者惟一键）',1,16)
RETURN
END

--其他参数检查及规范
IF ISNULL(@PageCurrent,0)<1 SET @PageCurrent=1
IF ISNULL(@PageSize,0)<1 SET @PageSize=10
IF ISNULL(@FieldShow,N'')=N'' SET @FieldShow=N'*'
IF ISNULL(@FieldOrder,N'')=N''
SET @FieldOrder=N''
ELSE
SET @FieldOrder=N'ORDER BY '+LTRIM(@FieldOrder)
IF ISNULL(@Where,N'')=N''
SET @Where=N''
ELSE
SET @Where=N'WHERE ('+@Where+N')'

--如果@PageCount为NULL值,则计算总页数(这样设计可以只在第一次计算总页数,以后调用时,把总页数传回给存储过程,避免再次计算总页数,对于不想计算总页数的处理而言,可以给@PageCount赋值)
/*IF @PageCount IS NULL
BEGIN*/
SET @sql=N'SELECT @PageCount=COUNT(*)'
+N' FROM '+@tbname
+N' '+@Where
EXEC sp_executesql @sql,N'@PageCount int OUTPUT',@PageCount OUTPUT
set @ItemCount = @PageCount
SET @PageCount=ceiling((@PageCount+@PageSize-1)/@PageSize)
if(@pagecount=0)
	set @pagecount=1
--END

--计算分页显示的TOPN值
DECLARE @TopN varchar(20),@TopN1 varchar(20)
SELECT @TopN=@PageSize,
@TopN1=@PageCurrent*@PageSize

print @topn1;
--第一页直接显示
IF @PageCurrent=1
EXEC(N'SELECT TOP '+@TopN
+N' '+@FieldShow
+N' FROM '+@tbname
+N' '+@Where
+N' '+@FieldOrder)
ELSE
BEGIN
SELECT @PageCurrent=@TopN1,
@sql=N'SELECT @n=@n-1,@s=CASE WHEN @n<'+@TopN
+N' THEN @s+N'',''+QUOTENAME(RTRIM(CAST('+@FieldKey
+N' as nvarchar(4000))),N'''''''') ELSE N'''' END FROM '+@tbname
+N' '+@Where
+N' '+@FieldOrder
SET ROWCOUNT @PageCurrent
print @sql
EXEC sp_executesql @sql,
N'@n int,@s nvarchar(4000) OUTPUT',
@PageCurrent,@sql OUTPUT

SET ROWCOUNT 0
IF @sql=N''
EXEC(N'SELECT TOP 0'
+N' '+@FieldShow
+N' FROM '+@tbname)
ELSE
BEGIN
SET @sql=STUFF(@sql,1,1,N'')

--执行查询
EXEC(N'SELECT TOP '+@TopN
+N' '+@FieldShow
+N' FROM '+@tbname
+N' WHERE '+@FieldKey
+N' IN('+@sql
+N') '+@FieldOrder)

END
END











GO
/****** Object:  StoredProcedure [dbo].[sp_处理审批]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


create PROCEDURE [dbo].[sp_处理审批]
    @流程ID INT,
    @节点ID INT,
    @审批人ID NVARCHAR(100),
    @审批人姓名 NVARCHAR(100),
    @处理结果 NVARCHAR(20), -- approved, rejected
    @审批意见 NVARCHAR(MAX) = NULL,
    @成功 BIT OUTPUT
AS
BEGIN
    SET NOCOUNT ON;
    BEGIN TRY
        BEGIN TRANSACTION;

        -- 插入审批记录
        INSERT INTO 审批记录表 (流程ID, 节点ID, 审批人ID, 审批人姓名, 处理结果, 审批意见)
        VALUES (@流程ID, @节点ID, @审批人ID, @审批人姓名, @处理结果, @审批意见);

        -- 更新节点状态
        UPDATE 流程节点表 
        SET 状态 = @处理结果,
            更新时间 = GETDATE()
        WHERE 节点ID = @节点ID;

        -- 更新流程状态
        IF @处理结果 = 'rejected'
        BEGIN
            -- 如果拒绝，流程结束
            UPDATE 流程表 
            SET 状态 = 'rejected',
                当前节点 = '已拒绝',
                更新时间 = GETDATE()
            WHERE 流程ID = @流程ID;
        END
        ELSE
        BEGIN
            -- 如果同意，推进到下一个节点
            DECLARE @当前步骤 INT;
            SELECT @当前步骤 = 步骤序号 FROM 流程节点表 WHERE 节点ID = @节点ID;

            DECLARE @下一节点ID INT;
            SELECT @下一节点ID = 节点ID 
            FROM 流程节点表 
            WHERE 流程ID = @流程ID AND 步骤序号 = @当前步骤 + 1;

            IF @下一节点ID IS NOT NULL
            BEGIN
                -- 还有下一个节点
                UPDATE 流程节点表 
                SET 状态 = 'processing',
                    更新时间 = GETDATE()
                WHERE 节点ID = @下一节点ID;

                UPDATE 流程表 
                SET 当前步骤 = @当前步骤 + 1,
                    当前节点 = (SELECT 节点名称 FROM 流程节点表 WHERE 节点ID = @下一节点ID),
                    更新时间 = GETDATE()
                WHERE 流程ID = @流程ID;
            END
            ELSE
            BEGIN
                -- 所有节点完成，流程结束
                UPDATE 流程表 
                SET 状态 = 'completed',
                    当前节点 = '已完成',
                    更新时间 = GETDATE()
                WHERE 流程ID = @流程ID;
            END
        END

        COMMIT TRANSACTION;
        SET @成功 = 1;
    END TRY
    BEGIN CATCH
        ROLLBACK TRANSACTION;
        SET @成功 = 0;
        THROW;
    END CATCH
END
GO
/****** Object:  StoredProcedure [dbo].[sp_创建流程]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[sp_创建流程]
    @流程标题 NVARCHAR(200),
    @流程描述 NVARCHAR(MAX) = NULL,
    @优先级 NVARCHAR(20) = 'normal',
    @发起人ID NVARCHAR(100),
    @发起人姓名 NVARCHAR(100),
    @审批人列表 NVARCHAR(MAX),
    @新流程ID INT OUTPUT,
    @已关联计划号 NVARCHAR(100) = NULL,
    @零件名称 NVARCHAR(100) = NULL,
    @零件编号 NVARCHAR(100) = NULL,
    @工序名称 NVARCHAR(100) = NULL
AS
BEGIN
    SET NOCOUNT ON;
    
    DECLARE @结果 INT = 0;
    DECLARE @消息 NVARCHAR(500) = '开始执行';
    
    PRINT '=== 存储过程调试信息 ===';
    PRINT '流程标题: ' + ISNULL(@流程标题, 'NULL');
    PRINT '发起人: ' + ISNULL(@发起人姓名, 'NULL');
    PRINT '审批人列表JSON: ' + ISNULL(@审批人列表, 'NULL');
    
    BEGIN TRY
        -- 验证必填字段
        IF ISNULL(@流程标题, '') = ''
        BEGIN
            SET @消息 = '流程标题不能为空';
            THROW 50000, @消息, 1;
        END

        -- 简化JSON验证，只检查是否为空
        IF ISNULL(@审批人列表, '') = ''
        BEGIN
            SET @消息 = '审批人列表不能为空';
            THROW 50000, @消息, 1;
        END

        BEGIN TRANSACTION;

        -- 插入流程主表
        INSERT INTO 流程表 (
            流程标题, 
            流程描述, 
            优先级, 
            状态, 
            发起人ID, 
            发起人姓名,
            当前节点,
            当前步骤,
            总步骤数,
            已关联计划号,
            零件名称,
            零件编号,
            工序名称,
            创建时间,
            更新时间
        )
        VALUES (
            @流程标题,
            ISNULL(@流程描述, ''),
            ISNULL(@优先级, 'normal'),
            'processing',  -- 直接设置为审批中
            @发起人ID,
            @发起人姓名,
            '待审批',
            1,  -- 从第一步开始
            1,  -- 初始总步骤
            @已关联计划号,
            @零件名称,
            @零件编号,
            @工序名称,
            GETDATE(),
            GETDATE()
        );

        -- 获取新创建的流程ID
        SET @新流程ID = SCOPE_IDENTITY();
        PRINT '插入流程表成功，新流程ID: ' + CAST(@新流程ID AS NVARCHAR(10));

        -- 方法：使用字符串分割方式处理审批人（避免JSON解析问题）
        DECLARE @审批人表 TABLE (
            步骤序号 INT IDENTITY(1,1),
            审批人ID NVARCHAR(100),
            审批人姓名 NVARCHAR(100)
        );

        -- 假设审批人列表格式为：用户ID1,用户姓名1|用户ID2,用户姓名2
        -- 这里我们创建一个临时的分隔符格式
        DECLARE @tempApprovers NVARCHAR(MAX);
        
        -- 如果JSON解析失败，使用默认的第一个审批人（发起人自己）
        IF ISJSON(@审批人列表) = 1
        BEGIN
            PRINT '尝试JSON解析...';
            -- 这里可以留空，因为我们主要用字符串方式
        END
        
        -- 使用发起人作为默认审批人（避免JSON问题）
        INSERT INTO @审批人表 (审批人ID, 审批人姓名)
        VALUES (@发起人ID, @发起人姓名);

        PRINT '使用默认审批人: ' + @发起人姓名;

        -- 插入流程节点
        INSERT INTO 流程节点表 (
            流程ID,
            节点名称,
            审批人ID,
            审批人姓名,
            步骤序号,
            状态,
            创建时间,
            更新时间
        )
        SELECT 
            @新流程ID,
            审批人姓名 + '审批' AS 节点名称,
            审批人ID,
            审批人姓名,
            步骤序号,
            CASE WHEN 步骤序号 = 1 THEN 'processing' ELSE 'pending' END AS 状态,
            GETDATE(),
            GETDATE()
        FROM @审批人表
        ORDER BY 步骤序号;

        PRINT '插入流程节点表完成';

        COMMIT TRANSACTION;
        
        SET @结果 = 1;
        SET @消息 = '流程创建成功，流程ID: ' + CAST(@新流程ID AS NVARCHAR(10));
        PRINT '事务提交成功';

        -- 返回结果
        SELECT 
            @结果 AS 结果,
            @新流程ID AS 新流程ID,
            @消息 AS 消息;
            
    END TRY
    BEGIN CATCH
        PRINT '捕获到错误: ' + ERROR_MESSAGE();
        
        IF @@TRANCOUNT > 0
        BEGIN
            ROLLBACK TRANSACTION;
            PRINT '事务已回滚';
        END

        SET @结果 = 0;
        SET @消息 = '错误: ' + ERROR_MESSAGE();

        -- 返回错误信息
        SELECT 
            @结果 AS 结果,
            NULL AS 新流程ID,
            @消息 AS 消息;
    END CATCH
END
GO
/****** Object:  StoredProcedure [dbo].[sp_创建流程_简化版]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- 创建不使用JSON的简化版本
CREATE PROCEDURE [dbo].[sp_创建流程_简化版]
    @流程标题 NVARCHAR(200),
    @流程描述 NVARCHAR(MAX) = NULL,
    @优先级 NVARCHAR(20) = 'normal',
    @发起人ID NVARCHAR(100),
    @发起人姓名 NVARCHAR(100),
    @审批人ID NVARCHAR(100),  -- 改为单个审批人ID
    @审批人姓名 NVARCHAR(100), -- 改为单个审批人姓名
    @新流程ID INT OUTPUT,
    @已关联计划号 NVARCHAR(100) = NULL,
    @零件名称 NVARCHAR(100) = NULL,
    @零件编号 NVARCHAR(100) = NULL,
    @工序名称 NVARCHAR(100) = NULL
AS
BEGIN
    SET NOCOUNT ON;
    
    DECLARE @结果 INT = 0;
    DECLARE @消息 NVARCHAR(500) = '开始执行';
    
    BEGIN TRY
        BEGIN TRANSACTION;

        -- 插入流程主表
        INSERT INTO 流程表 (
            流程标题, 
            流程描述, 
            优先级, 
            状态, 
            发起人ID, 
            发起人姓名,
            当前节点,
            当前步骤,
            总步骤数,
            已关联计划号,
            零件名称,
            零件编号,
            工序名称,
            创建时间,
            更新时间
        )
        VALUES (
            @流程标题,
            ISNULL(@流程描述, ''),
            ISNULL(@优先级, 'normal'),
            'processing',
            @发起人ID,
            @发起人姓名,
            @审批人姓名 + '审批',
            1,
            1,
            @已关联计划号,
            @零件名称,
            @零件编号,
            @工序名称,
            GETDATE(),
            GETDATE()
        );

        -- 获取新创建的流程ID
        SET @新流程ID = SCOPE_IDENTITY();

        -- 插入流程节点
        INSERT INTO 流程节点表 (
            流程ID,
            节点名称,
            审批人ID,
            审批人姓名,
            步骤序号,
            状态,
            创建时间,
            更新时间
        )
        VALUES (
            @新流程ID,
            @审批人姓名 + '审批',
            @审批人ID,
            @审批人姓名,
            1,
            'processing',
            GETDATE(),
            GETDATE()
        );

        COMMIT TRANSACTION;
        
        SET @结果 = 1;
        SET @消息 = '流程创建成功，流程ID: ' + CAST(@新流程ID AS NVARCHAR(10));

        -- 返回结果
        SELECT 
            @结果 AS 结果,
            @新流程ID AS 新流程ID,
            @消息 AS 消息;
            
    END TRY
    BEGIN CATCH
        IF @@TRANCOUNT > 0
            ROLLBACK TRANSACTION;

        SET @结果 = 0;
        SET @消息 = '错误: ' + ERROR_MESSAGE();

        SELECT 
            @结果 AS 结果,
            NULL AS 新流程ID,
            @消息 AS 消息;
    END CATCH
END
GO
/****** Object:  StoredProcedure [dbo].[sp_获取待处理任务]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


create PROCEDURE [dbo].[sp_获取待处理任务]
    @审批人ID NVARCHAR(100)
AS
BEGIN
    SET NOCOUNT ON;
    
    SELECT 
        p.流程ID,
        p.流程标题,
        p.流程描述,
        p.优先级,
        p.发起人姓名 as 申请人,
        p.创建时间 as 申请时间,
        p.已关联计划号, 
        p.零件名称, 
        p.零件编号,
        p.工序名称,
        pn.截止时间,
        pn.节点名称 as 当前节点,
        pn.节点ID
    FROM 流程表 p
    INNER JOIN 流程节点表 pn ON p.流程ID = pn.流程ID
    WHERE pn.审批人ID = @审批人ID
    AND pn.状态 = 'processing'
    AND p.状态 = 'processing'
    ORDER BY 
        CASE p.优先级 
            WHEN 'urgent' THEN 1
            WHEN 'high' THEN 2
            ELSE 3
        END,
        pn.截止时间;
END
GO
/****** Object:  StoredProcedure [dbo].[sp_获取流程详情]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


create PROCEDURE [dbo].[sp_获取流程详情]
    @流程ID INT
AS
BEGIN
    SET NOCOUNT ON;
    
    -- 流程基本信息
    DECLARE @流程信息 NVARCHAR(MAX);
    SELECT @流程信息 = (
        SELECT 
            p.流程ID,
            p.流程标题,
            p.流程描述,
            p.优先级,
            p.状态,
            p.发起人姓名,
            p.当前节点,
            p.当前步骤,
            p.总步骤数,
            p.已关联计划号,
            p.零件名称,
            p.零件编号,
            p.工序名称,
            CONVERT(NVARCHAR(19), p.创建时间, 120) as 发起时间,
            CONVERT(NVARCHAR(19), p.更新时间, 120) as 更新时间
        FROM 流程表 p
        WHERE p.流程ID = @流程ID
        FOR JSON PATH, WITHOUT_ARRAY_WRAPPER
    );

    -- 审批步骤
    DECLARE @步骤信息 NVARCHAR(MAX);
    SELECT @步骤信息 = (
        SELECT 
            节点名称 as 标题,
            步骤序号,
            审批人姓名,
            状态,
            CASE 
                WHEN 步骤序号 < (SELECT 当前步骤 FROM 流程表 WHERE 流程ID = @流程ID) THEN '已完成'
                WHEN 步骤序号 = (SELECT 当前步骤 FROM 流程表 WHERE 流程ID = @流程ID) THEN '进行中'
                ELSE '未开始'
            END as 状态描述,
            CONVERT(NVARCHAR(19), 创建时间, 120) as 描述
        FROM 流程节点表 
        WHERE 流程ID = @流程ID 
        ORDER BY 步骤序号
        FOR JSON PATH
    );

    -- 审批记录
    DECLARE @审批记录 NVARCHAR(MAX);
    SELECT @审批记录 = (
        SELECT 
            pn.节点名称,
            ar.审批人姓名,
            ar.处理结果,
            ar.审批意见,
            CONVERT(NVARCHAR(19), ar.处理时间, 120) as 时间
        FROM 审批记录表 ar
        INNER JOIN 流程节点表 pn ON ar.节点ID = pn.节点ID
        WHERE ar.流程ID = @流程ID
        ORDER BY ar.处理时间 DESC
        FOR JSON PATH
    );

    -- 返回单个JSON对象
    SELECT 
        @流程信息 as 流程信息,
        @步骤信息 as 步骤信息,
        @审批记录 as 审批记录
    FOR JSON PATH, WITHOUT_ARRAY_WRAPPER;
END
GO
/****** Object:  StoredProcedure [dbo].[sp_获取我的流程]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


create PROCEDURE [dbo].[sp_获取我的流程]
    @发起人ID NVARCHAR(100),
    @状态 NVARCHAR(20) = NULL
AS
BEGIN
    SET NOCOUNT ON;
    
    SELECT 
        p.流程ID,
        p.流程标题,
        p.流程描述,
        p.优先级,
        p.状态,
        p.当前节点,
        p.当前步骤,
        p.总步骤数,
        p.创建时间 as 发起时间,
        p.更新时间
    FROM 流程表 p
    WHERE p.发起人ID = @发起人ID
    AND (@状态 IS NULL OR p.状态 = @状态)
    ORDER BY p.更新时间 DESC;
END
GO
/****** Object:  StoredProcedure [dbo].[sp_获取最近处理任务]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


create PROCEDURE [dbo].[sp_获取最近处理任务]
    @审批人ID NVARCHAR(100)
AS
BEGIN
    SET NOCOUNT ON;
    
    SELECT 
        ar.记录ID,
        p.流程ID,
        p.流程标题 as 流程名称,
        p.发起人姓名 as 申请人,
        ar.审批人姓名 as 处理人,
        ar.处理结果,
        CASE ar.处理结果 
            WHEN 'approved' THEN '同意'
            WHEN 'rejected' THEN '拒绝'
            ELSE ar.处理结果
        END as 处理结果文本,
        ar.审批意见,
        ar.处理时间,
        CONVERT(NVARCHAR(10), ar.处理时间, 120) as 处理日期,
        pn.节点名称 as 审批节点,
        p.优先级
    FROM 审批记录表 ar
    INNER JOIN 流程节点表 pn ON ar.节点ID = pn.节点ID
    INNER JOIN 流程表 p ON ar.流程ID = p.流程ID
    WHERE ar.审批人ID = @审批人ID
    ORDER BY ar.处理时间 DESC;
END
GO
/****** Object:  StoredProcedure [dbo].[sp_提交流程]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


create PROCEDURE [dbo].[sp_提交流程]
    @流程ID INT,
    @成功 BIT OUTPUT
AS
BEGIN
    SET NOCOUNT ON;
    BEGIN TRY
        -- 检查流程是否存在且状态为draft
        IF NOT EXISTS (SELECT 1 FROM 流程表 WHERE 流程ID = @流程ID AND 状态 = 'draft')
        BEGIN
            SET @成功 = 0;
            RETURN;
        END

        -- 更新流程状态
        UPDATE 流程表 
        SET 状态 = 'processing',
            更新时间 = GETDATE()
        WHERE 流程ID = @流程ID;

        -- 更新第一个审批节点状态
        UPDATE 流程节点表 
        SET 状态 = 'processing',
            更新时间 = GETDATE()
        WHERE 流程ID = @流程ID AND 步骤序号 = 1;

        SET @成功 = 1;
    END TRY
    BEGIN CATCH
        SET @成功 = 0;
        THROW;
    END CATCH
END
GO
/****** Object:  StoredProcedure [dbo].[sp_完成流程]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


create PROCEDURE [dbo].[sp_完成流程]
    @流程ID INT,
    @发起人ID NVARCHAR(100),
    @发起人姓名 NVARCHAR(100),
    @完成类型 NVARCHAR(20), -- completed, cancelled
    @完成原因 NVARCHAR(500),
    @成功 BIT OUTPUT
AS
BEGIN
    SET NOCOUNT ON;
    BEGIN TRY
        BEGIN TRANSACTION;

        -- 检查流程状态和权限（只有发起人可以完结）
        IF NOT EXISTS (
            SELECT 1 FROM 流程表 
            WHERE 流程ID = @流程ID 
            AND 发起人ID = @发起人ID
            AND 状态 IN ('draft', 'processing')
        )
        BEGIN
            SET @成功 = 0;
            RETURN;
        END

        -- 记录完结信息
        INSERT INTO 流程完成记录表 (
            流程ID, 发起人ID, 发起人姓名, 完成类型, 完成原因
        )
        VALUES (@流程ID, @发起人ID, @发起人姓名, @完成类型, @完成原因);

        -- 更新流程状态
        UPDATE 流程表 
        SET 状态 = @完成类型,
            当前节点 = '已完结',
            完成人 = @发起人姓名,
            完成时间 = GETDATE(),
            完成原因 = @完成原因,
            完成类型 = @完成类型,
            更新时间 = GETDATE()
        WHERE 流程ID = @流程ID;

        -- 更新所有进行中的节点状态
        UPDATE 流程节点表 
        SET 状态 = 'cancelled',
            更新时间 = GETDATE()
        WHERE 流程ID = @流程ID 
        AND 状态 = 'processing';

        -- 记录系统日志
        INSERT INTO 审批记录表 (流程ID, 节点ID, 审批人ID, 审批人姓名, 处理结果, 审批意见)
        SELECT 
            @流程ID, 节点ID, 'system', '系统', 'completed', 
            CONCAT('流程已被发起人完结。类型: ', 
                   CASE @完成类型 WHEN 'completed' THEN '完成' ELSE '取消' END,
                   '。原因: ', ISNULL(@完成原因, '无'))
        FROM 流程节点表 
        WHERE 流程ID = @流程ID 
        AND 状态 = 'processing';

        COMMIT TRANSACTION;
        SET @成功 = 1;
    END TRY
    BEGIN CATCH
        ROLLBACK TRANSACTION;
        SET @成功 = 0;
        THROW;
    END CATCH
END
GO
/****** Object:  StoredProcedure [dbo].[sp_转办流程]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


create PROCEDURE [dbo].[sp_转办流程]
    @流程ID INT,
    @节点ID INT,
    @原审批人ID NVARCHAR(100),
    @原审批人姓名 NVARCHAR(100),
    @新审批人ID NVARCHAR(100),
    @新审批人姓名 NVARCHAR(100),
    @转办原因 NVARCHAR(500),
    @成功 BIT OUTPUT
AS
BEGIN
    SET NOCOUNT ON;
    BEGIN TRY
        BEGIN TRANSACTION;

        -- 检查流程和节点状态
        IF NOT EXISTS (
            SELECT 1 FROM 流程表 p
            INNER JOIN 流程节点表 pn ON p.流程ID = pn.流程ID
            WHERE p.流程ID = @流程ID 
            AND pn.节点ID = @节点ID
            AND pn.状态 = 'processing'
            AND p.状态 = 'processing'
            AND pn.审批人ID = @原审批人ID
        )
        BEGIN
            SET @成功 = 0;
            RETURN;
        END

        -- 记录转办信息
        INSERT INTO 流程转办表 (
            流程ID, 原节点ID, 原审批人ID, 原审批人姓名,
            新审批人ID, 新审批人姓名, 转办原因
        )
        VALUES (
            @流程ID, @节点ID, @原审批人ID, @原审批人姓名,
            @新审批人ID, @新审批人姓名, @转办原因
        );

        DECLARE @转办ID INT = SCOPE_IDENTITY();

        -- 更新节点审批人
        UPDATE 流程节点表 
        SET 审批人ID = @新审批人ID,
            审批人姓名 = @新审批人姓名,
            是否转办 = 1,
            转办ID = @转办ID,
            更新时间 = GETDATE()
        WHERE 节点ID = @节点ID;

        -- 记录审批记录（需要创建审批记录表）
        INSERT INTO 审批记录表 (流程ID, 节点ID, 审批人ID, 审批人姓名, 处理结果, 审批意见)
        VALUES (@流程ID, @节点ID, @原审批人ID, @原审批人姓名, 'transferred', 
                CONCAT('流程已转办给 ', @新审批人姓名, '。原因: ', ISNULL(@转办原因, '无')));

        COMMIT TRANSACTION;
        SET @成功 = 1;
    END TRY
    BEGIN CATCH
        ROLLBACK TRANSACTION;
        SET @成功 = 0;
        THROW;
    END CATCH
END
GO
/****** Object:  StoredProcedure [dbo].[TV_视图看板_查询]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
create PROCEDURE [dbo].[TV_视图看板_查询]
AS 

SELECT  [项目]
      ,[生产订单号]
      ,[计划号]
      ,[产成品物料编号]
      ,[物料名称]
      ,[计划数量]
      ,[加急状态]
      ,[优先]
      ,[齐套状态]
      ,[拣配日期]
      ,[预计齐套日期]
  FROM SAP.SBO_YL.dbo.UBT_MES_TASK_1
GO
/****** Object:  StoredProcedure [dbo].[TV_视图看板2楼_查询]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[TV_视图看板2楼_查询]
AS 

SELECT top 20  [项目]
      ,[生产订单号]
      ,[计划号]
      ,[产成品物料编号]
      ,[物料名称]
      ,[计划数量]
      ,[加急状态]
      ,[优先]
      ,[齐套状态]
      ,[拣配日期]
      ,[预计齐套日期]
  FROM SAP.SBO_YL.dbo.UBT_MES_TASK_2
GO
/****** Object:  StoredProcedure [dbo].[TV_视图看板仓库_查询]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[TV_视图看板仓库_查询]
AS 

SELECT  [项目]
      ,[生产订单号]
      ,[计划号]
      ,[产成品物料编号]
      ,[物料名称]
      ,[计划数量]
      ,[加急状态]
      ,[优先]
      ,[齐套状态]
      ,[拣配日期]
      ,[预计齐套日期]
  FROM SAP.SBO_YL.dbo.UBT_MES_TASK2_2
GO
/****** Object:  StoredProcedure [dbo].[update_MyTask]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[update_MyTask]
AS
BEGIN
    SET NOCOUNT ON;

    BEGIN TRY
        BEGIN TRANSACTION;
		
		--UPDATE m
  --      SET m.加急状态 = 0
  --      FROM [dbo].[质量检验_质检任务_SAP] m where 加急状态 > 0
  --      UPDATE m
  --      SET m.加急状态 = 1
  --      FROM [dbo].[质量检验_质检任务_SAP] m
  --      INNER JOIN SAP.SBO_YL.dbo.ubt_OPKL_UrgentMaterials u
  --          ON u.物料编码 = m.物料编码
		--	where  u.物料编码 = m.物料编码;
		UPDATE m
        SET m.加急总数 = 0 , m.加急状态 = 0
        FROM [dbo].[质量检验_质检任务_SAP] m where isnull(加急总数,0) > 0
        UPDATE m
        SET m.加急总数 = u.加急数量 ,  m.加急状态 = 1
        FROM [dbo].[质量检验_质检任务_SAP] m
        INNER JOIN SAP.SBO_YL.dbo.ubt_OPKL_UrgentMaterials u
            ON m.物料编码 = u.物料编码;
		UPDATE m
        SET m.入库数量 = u.已完工数量
        FROM [dbo].[MES_接口_生产计划] m
        INNER JOIN SAP.SBO_YL.dbo.UBT_OWOR_OIGN u
            ON m.订单编号 = u.DocEntry;

		UPDATE m
        SET m.发货状态 = 0,m.加急状态 = 0
        FROM [dbo].[MES_接口_生产计划] m where 发货状态 = 1
        UPDATE m
        SET m.发货状态 = 1
        FROM [dbo].[MES_接口_生产计划] m
        INNER JOIN SAP.SBO_YL.dbo.UBT_OPKL_UrgentMaterials u
            ON m.物料编号 = u.物料编码 

		UPDATE m
        SET m.加急总数 = 0 , m.加急状态 = 0
        FROM [dbo].[MES_接口_生产计划] m where isnull(加急总数,0) > 0
        UPDATE m
        SET m.加急总数 = u.加急数量 ,  m.加急状态 = 1
        FROM [dbo].[MES_接口_生产计划] m
        INNER JOIN SAP.SBO_YL.dbo.ubt_OPKL_UrgentMaterials u
            ON m.物料编号 = u.物料编码;

		--UPDATE m
  --      SET m.要求发货日期 = 0
  --      FROM [dbo].[MES_接口_生产计划] m where 发货状态 = 1
        UPDATE m
        SET m.要求发货日期 = u.U_XSReDeDate
        FROM [dbo].[MES_接口_生产计划] m
        INNER JOIN SAP.SBO_YL.dbo.UBT_OPKL_UrgentMaterials_ZP u
            ON m.订单编号 = u.DocEntry;
        COMMIT TRANSACTION;
		
        PRINT '成功更新 ' + CAST(@@ROWCOUNT AS VARCHAR) + ' 条记录。';

    END TRY
    BEGIN CATCH
        IF @@TRANCOUNT > 0
            ROLLBACK TRANSACTION;

        PRINT '更新失败: ' + ERROR_MESSAGE();
        THROW;
    END CATCH

	BEGIN TRY
        BEGIN TRANSACTION;

        UPDATE m
        SET m.齐套 = 1
        FROM [MES_接口_生产计划] m
        INNER JOIN SAP.SBO_YL.dbo.UBT_OPKL_CompleteSet u
            ON m.订单编号 = u.生产订单号
			where u.齐套状态 = '齐套' 
		UPDATE m
		SET m.发料状态 = 1
        FROM [MES_接口_生产计划] m
        INNER JOIN SAP.SBO_YL.dbo.UBT_OPKL_CompleteSet u
            ON m.订单编号 = u.生产订单号
			where u.发料状态 = '发料齐套'
		UPDATE m
		SET m.发料状态 = 2
        FROM [MES_接口_生产计划] m
        INNER JOIN SAP.SBO_YL.dbo.UBT_OPKL_CompleteSet u
            ON m.订单编号 = u.生产订单号
			where u.发料状态 = '发料缺件' 
		UPDATE m
		SET m.拣配状态 = 1
        FROM [MES_接口_生产计划] m
        INNER JOIN SAP.SBO_YL.dbo.UBT_OPKL_CompleteSet u
            ON m.订单编号 = u.生产订单号
			where u.拣配状态 = '已拣配'
		UPDATE r
        SET r.任务状态 = 1
        FROM MES_接口_生产计划_生产任务  r
        INNER JOIN SAP.SBO_YL.dbo.UBT_OPKL_CompleteSet u
            ON r.订单编号 = u.生产订单号
			where u.执行状态 = '可执行'  and  r.订单行号 = 1  and isnull(r.任务状态,0)<1
        COMMIT TRANSACTION;

        PRINT '成功更新 ' + CAST(@@ROWCOUNT AS VARCHAR) + ' 条记录。';

    END TRY
    BEGIN CATCH
        IF @@TRANCOUNT > 0
            ROLLBACK TRANSACTION;

        PRINT '更新失败: ' + ERROR_MESSAGE();
        THROW;
    END CATCH
	BEGIN TRY
        BEGIN TRANSACTION;

        UPDATE m
        SET m.单据状态 = '已取消'
        FROM [MES_接口_生产计划] m
        INNER JOIN SAP.SBO_YL.dbo.UBT_OWOR u
            ON m.订单编号 = u.生产订单号
			where u.单据状态 = '已取消' OR u.单据状态 = '已结算'
        COMMIT TRANSACTION;

        PRINT '成功更新 ' + CAST(@@ROWCOUNT AS VARCHAR) + ' 条记录。';

    END TRY
    BEGIN CATCH
        IF @@TRANCOUNT > 0
            ROLLBACK TRANSACTION;

        PRINT '更新失败: ' + ERROR_MESSAGE();
        THROW;
    END CATCH
END
GO
/****** Object:  StoredProcedure [dbo].[usp_BatchValidateWorkTime]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[usp_BatchValidateWorkTime]
    @RecordAIDs NVARCHAR(MAX),
    @Operator NVARCHAR(50),
    @Editor NVARCHAR(50),
    @SuccessCount INT OUTPUT,
    @FailCount INT OUTPUT,
    @ResultDetails NVARCHAR(MAX) OUTPUT
AS
BEGIN
    SET NOCOUNT ON;
    
    PRINT '=== usp_BatchValidateWorkTime 开始执行 ===';
    PRINT 'RecordAIDs: ' + @RecordAIDs;
    
    -- 1. 拆分记录ID到临时表
    CREATE TABLE #TempRecords (AID INT PRIMARY KEY, Processed BIT DEFAULT 0);
    
    INSERT INTO #TempRecords (AID)
    SELECT CAST(value AS INT) 
    FROM STRING_SPLIT(@RecordAIDs, ',')
    WHERE ISNUMERIC(value) = 1;
    
    PRINT '拆分后记录数: ' + CAST(@@ROWCOUNT AS NVARCHAR);
    
    -- 2. 初始化计数器
    SET @SuccessCount = 0;
    SET @FailCount = 0;
    
    DECLARE @ResultTable TABLE (
        AID INT,
        Success BIT,
        Message NVARCHAR(500),
        UploadMinutes DECIMAL(18,2),
        WorkType NVARCHAR(20),
        CalculationDetail NVARCHAR(MAX)
    );
    
    -- ========== 如果没有记录被拆分，直接返回 ==========
    IF NOT EXISTS (SELECT 1 FROM #TempRecords)
    BEGIN
        SET @ResultDetails = '{"SuccessCount":0,"FailCount":0,"Details":[],"Message":"没有有效的记录ID"}';
        SELECT 0 AS SuccessCount, 0 AS FailCount, @ResultDetails AS ResultDetails;
        DROP TABLE #TempRecords;
        RETURN;
    END
    
    -- 3. 预计算比例系数（只针对非加班类型）
    DECLARE @OperatorGroups TABLE (
        OperatorName NVARCHAR(50),
        WorkDate DATE,
        StandardHours DECIMAL(10,2),
        Ratio DECIMAL(18,6),
        TotalMinutes DECIMAL(18,2)
    );
    
    INSERT INTO @OperatorGroups (OperatorName, WorkDate, StandardHours, Ratio, TotalMinutes)
    SELECT DISTINCT 
        v.操作人,
        TRY_CAST(v.开始时间 AS DATE) AS WorkDate,
        CASE 
            WHEN v.当日班次最小标准工时 > 0 THEN v.当日班次最小标准工时 
            ELSE ISNULL(v.班次标准工时, 8)
        END AS StandardHours,
        0 AS Ratio,
        0 AS TotalMinutes
    FROM #TempRecords t
    INNER JOIN View_生产工时视图 v ON t.AID = v.AID
    WHERE v.操作类别 NOT IN ('加班', '休息日加班', '法定休息日加班')
        AND v.总时长 > 0
        AND TRY_CAST(v.开始时间 AS DATE) IS NOT NULL;
    
    -- 更新比例系数
    DECLARE @OpName NVARCHAR(50), @WDate DATE, @StdHours DECIMAL(10,2), @Ratio DECIMAL(18,6), @TotalMin DECIMAL(18,2);
    
    DECLARE group_cursor CURSOR FOR 
        SELECT OperatorName, WorkDate, StandardHours FROM @OperatorGroups;
    
    OPEN group_cursor;
    FETCH NEXT FROM group_cursor INTO @OpName, @WDate, @StdHours;
    
    WHILE @@FETCH_STATUS = 0
    BEGIN
        EXEC usp_CalculateDailyRatio 
            @OperatorName = @OpName,
            @WorkDate = @WDate,
            @StandardHours = @StdHours,
            @Ratio = @Ratio OUTPUT,
            @TotalMinutes = @TotalMin OUTPUT;
        
        UPDATE @OperatorGroups 
        SET Ratio = @Ratio, TotalMinutes = @TotalMin
        WHERE OperatorName = @OpName AND WorkDate = @WDate;
        
        FETCH NEXT FROM group_cursor INTO @OpName, @WDate, @StdHours;
    END
    
    CLOSE group_cursor;
    DEALLOCATE group_cursor;
    
    -- ========== 删除您之前添加的无用UPDATE ==========
    -- 不需要那行代码
    
    -- 4. 逐条处理记录
    DECLARE @CurrentAID INT, @UploadMinutes DECIMAL(18,2), @WorkType NVARCHAR(20), @CalcDetail NVARCHAR(MAX);
    DECLARE @WorkCategory NVARCHAR(50), @TotalSeconds DECIMAL(18,2);
    
    DECLARE record_cursor CURSOR FOR SELECT AID FROM #TempRecords WHERE Processed = 0;
    
    OPEN record_cursor;
    FETCH NEXT FROM record_cursor INTO @CurrentAID;
    
    WHILE @@FETCH_STATUS = 0
    BEGIN
        PRINT '正在处理 AID: ' + CAST(@CurrentAID AS NVARCHAR);
        
        BEGIN TRY
            -- ========== 先获取记录的操作类别和总时长 ==========
            SELECT 
                @WorkCategory = v.操作类别,
                @TotalSeconds = v.总时长
            FROM View_生产工时视图 v
            WHERE v.AID = @CurrentAID;
            
            -- ========== 判断是否为加班类型 ==========
            IF @WorkCategory IN ('加班', '休息日加班', '法定休息日加班')
            BEGIN
                -- ✅ 加班类型：直接使用总时长计算，不调用 usp_CalculateUploadMinutes
                SET @UploadMinutes = @TotalSeconds / 60.0;
                SET @WorkType = '加班';
                
                -- 构建计算详情
                SET @CalcDetail = (
                    SELECT 
                        @CurrentAID AS RecordAID,
                        @WorkCategory AS WorkCategory,
                        @TotalSeconds AS TotalSeconds,
                        @TotalSeconds / 60.0 AS TotalMinutes,
                        @UploadMinutes AS UploadMinutes,
                        @WorkType AS WorkType,
                        GETDATE() AS CalculateTime,
                        '班次外加班直接计算' AS Note
                    FOR JSON PATH, WITHOUT_ARRAY_WRAPPER
                );
                
                PRINT '  加班类型 - UploadMinutes: ' + CAST(@UploadMinutes AS NVARCHAR);
                
                INSERT INTO @ResultTable (AID, Success, Message, UploadMinutes, WorkType, CalculationDetail)
                VALUES (@CurrentAID, 1, '计算成功', @UploadMinutes, @WorkType, @CalcDetail);
                SET @SuccessCount = @SuccessCount + 1;
            END
            ELSE
            BEGIN
                -- 非加班类型：使用原有的存储过程计算
                EXEC usp_CalculateUploadMinutes 
                    @RecordAID = @CurrentAID,
                    @UploadMinutes = @UploadMinutes OUTPUT,
                    @WorkType = @WorkType OUTPUT,
                    @CalculationDetail = @CalcDetail OUTPUT;
                
                PRINT '  非加班类型 - UploadMinutes: ' + CAST(@UploadMinutes AS NVARCHAR) + ', WorkType: ' + @WorkType;
                
                -- 处理各种结果
                IF @WorkType = '跳过SAP'
                BEGIN
                    INSERT INTO @ResultTable (AID, Success, Message, UploadMinutes, WorkType, CalculationDetail)
                    VALUES (@CurrentAID, 1, '总时长为0，跳过SAP上传', 0, @WorkType, @CalcDetail);
                    SET @SuccessCount = @SuccessCount + 1;
                    PRINT '  成功: 总时长为0，跳过SAP上传';
                END
                ELSE IF @UploadMinutes < 0 OR @WorkType = '无效'
                BEGIN
                    DECLARE @ErrorMsg NVARCHAR(500) = ISNULL(JSON_VALUE(@CalcDetail, '$.Error'), '工时计算失败');
                    INSERT INTO @ResultTable (AID, Success, Message, UploadMinutes, WorkType, CalculationDetail)
                    VALUES (@CurrentAID, 0, @ErrorMsg, @UploadMinutes, @WorkType, @CalcDetail);
                    SET @FailCount = @FailCount + 1;
                    PRINT '  失败: ' + @ErrorMsg;
                END
                ELSE
                BEGIN
                    INSERT INTO @ResultTable (AID, Success, Message, UploadMinutes, WorkType, CalculationDetail)
                    VALUES (@CurrentAID, 1, '计算成功', @UploadMinutes, @WorkType, @CalcDetail);
                    SET @SuccessCount = @SuccessCount + 1;
                    PRINT '  成功: ' + CAST(@UploadMinutes AS NVARCHAR) + '分钟';
                END
            END
            
            UPDATE #TempRecords SET Processed = 1 WHERE AID = @CurrentAID;
            
        END TRY
        BEGIN CATCH
            SET @FailCount = @FailCount + 1;
            INSERT INTO @ResultTable (AID, Success, Message)
            VALUES (@CurrentAID, 0, ERROR_MESSAGE());
            PRINT '  异常: ' + ERROR_MESSAGE();
        END CATCH
        
        FETCH NEXT FROM record_cursor INTO @CurrentAID;
    END
    
    CLOSE record_cursor;
    DEALLOCATE record_cursor;
    
    PRINT '处理完成 - 成功: ' + CAST(@SuccessCount AS NVARCHAR) + ', 失败: ' + CAST(@FailCount AS NVARCHAR);
    
    -- ========== 5. 构建结果JSON ==========
    SET @ResultDetails = (
        SELECT 
            @SuccessCount AS SuccessCount,
            @FailCount AS FailCount,
            ISNULL((SELECT * FROM @ResultTable FOR JSON PATH), '[]') AS Details,
            ISNULL((SELECT * FROM @OperatorGroups FOR JSON PATH), '[]') AS RatioGroups
        FOR JSON PATH, WITHOUT_ARRAY_WRAPPER
    );
    
    PRINT 'ResultDetails: ' + @ResultDetails;
    
    -- ========== 6. 返回结果集 ==========
    SELECT 
        @SuccessCount AS SuccessCount,
        @FailCount AS FailCount,
        @ResultDetails AS ResultDetails;
    
    -- 7. 清理
    DROP TABLE #TempRecords;
    
    PRINT '=== usp_BatchValidateWorkTime 执行完成 ===';
END
GO
/****** Object:  StoredProcedure [dbo].[usp_CalculateDailyRatio]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[usp_CalculateDailyRatio]
    @OperatorName NVARCHAR(50),
    @WorkDate DATE,
    @StandardHours DECIMAL(10,2) = 8,
    @Ratio DECIMAL(18,6) OUTPUT,
    @TotalMinutes DECIMAL(18,2) OUTPUT
AS
BEGIN
    SET NOCOUNT ON;
    
    DECLARE @TotalSeconds DECIMAL(18,2) = 0;
    
    SELECT @TotalSeconds = ISNULL(SUM( 总时长), 0)
    FROM View_生产工时视图
    WHERE 操作人 = @OperatorName
        AND CONVERT(DATE, 开始时间) = @WorkDate
        AND 操作类别 NOT IN ('加班', '休息日加班', '法定节假日加班')
        AND 总时长 > 0
		and isNull(阶段标识,0) != -1
		and 订单号 <> 3886
    
    SET @TotalMinutes = @TotalSeconds / 60.0;
    
    -- ========== 修复：当日总工时为0时，比例系数为1 ==========
    IF @TotalMinutes > 0 AND @StandardHours > 0
        SET @Ratio = (@StandardHours * 60) / @TotalMinutes;
    ELSE
    BEGIN
        SET @Ratio = 1.0;
        SET @TotalMinutes = 0;
    END
END
GO
/****** Object:  StoredProcedure [dbo].[usp_CalculateShiftTime]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE   PROCEDURE [dbo].[usp_CalculateShiftTime]
    @开始时间 DATETIME,
    @结束时间 DATETIME,
    @班次开始 TIME,
    @班次结束 TIME,
    @班次内秒数 INT OUTPUT,
    @班次外秒数 INT OUTPUT
AS
BEGIN
    SET NOCOUNT ON;
    
    SET @班次内秒数 = 0;
    SET @班次外秒数 = 0;
    
    -- 如果结束时间早于开始时间，交换
    IF @结束时间 < @开始时间
    BEGIN
        DECLARE @Temp DATETIME = @开始时间;
        SET @开始时间 = @结束时间;
        SET @结束时间 = @Temp;
    END
    
    -- 如果开始时间等于结束时间，直接返回
    IF @开始时间 = @结束时间
    BEGIN
        RETURN;
    END
    
    DECLARE @当前时间 DATETIME = @开始时间;
    DECLARE @循环计数 INT = 0;
    DECLARE @最大循环 INT = 1000;  -- 防止无限循环
    
    WHILE @当前时间 < @结束时间 AND @循环计数 < @最大循环
    BEGIN
        SET @循环计数 = @循环计数 + 1;
        
        DECLARE @当天日期 DATE = CAST(@当前时间 AS DATE);
        DECLARE @当天班次开始 DATETIME = CAST(@当天日期 AS DATETIME) + CAST(@班次开始 AS DATETIME);
        DECLARE @当天班次结束 DATETIME;
        
        -- 判断是否跨天
        IF @班次结束 < @班次开始
            SET @当天班次结束 = CAST(DATEADD(DAY, 1, @当天日期) AS DATETIME) + CAST(@班次结束 AS DATETIME);
        ELSE
            SET @当天班次结束 = CAST(@当天日期 AS DATETIME) + CAST(@班次结束 AS DATETIME);
        
        -- 计算这一段的时间
        DECLARE @段结束 DATETIME = CASE 
            WHEN @结束时间 < @当天班次结束 THEN @结束时间 
            ELSE @当天班次结束 
        END;
        
        -- ========== 关键修复：如果段时间为0，跳过 ==========
        IF @段结束 <= @当前时间
        BEGIN
            -- 强制推进到下一段的开始
            IF @当前时间 < @当天班次开始 AND @当天班次开始 < @结束时间
                SET @当前时间 = @当天班次开始;
            ELSE IF @当前时间 < @当天班次结束 AND @当天班次结束 < @结束时间
                SET @当前时间 = @当天班次结束;
            ELSE
                SET @当前时间 = DATEADD(SECOND, 1, @当前时间);  -- 强制前进1秒
            CONTINUE;
        END
        
        -- 判断是否在班次内
        IF @当前时间 >= @当天班次开始 AND @当前时间 < @当天班次结束
        BEGIN
            SET @班次内秒数 = @班次内秒数 + DATEDIFF(SECOND, @当前时间, @段结束);
        END
        ELSE
        BEGIN
            SET @班次外秒数 = @班次外秒数 + DATEDIFF(SECOND, @当前时间, @段结束);
        END
        
        SET @当前时间 = @段结束;
    END
    
    -- 如果因为循环次数限制退出，记录日志
    IF @循环计数 >= @最大循环
    BEGIN
        PRINT '警告: usp_CalculateShiftTime 达到最大循环次数';
    END
END
GO
/****** Object:  StoredProcedure [dbo].[usp_CalculateUploadMinutes]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[usp_CalculateUploadMinutes]
    @RecordAID INT,
    @UploadMinutes DECIMAL(18,2) OUTPUT,
    @WorkType NVARCHAR(20) OUTPUT,
    @CalculationDetail NVARCHAR(MAX) OUTPUT
AS
BEGIN
    SET NOCOUNT ON;
    
    DECLARE @操作类别 NVARCHAR(50),
            @总时长 DECIMAL(18,2),
            @绑定设备数 INT,
            @操作人 NVARCHAR(50),
            @工位名称 NVARCHAR(50),
            @开始时间 DATETIME,
            @结束时间 DATETIME,
            @当日班次最小标准工时 DECIMAL(10,2),
            @班次标准工时 DECIMAL(10,2),
            @班次 NVARCHAR(20);
    
    SELECT 
        @操作类别 = 操作类别,
        @总时长 = ISNULL(总时长, 0),
        @绑定设备数 = ISNULL(绑定设备数, 1),
        @操作人 = 操作人,
        @工位名称 = 工位名称,
        @开始时间 = ISNULL(TRY_CAST(开始时间 AS DATETIME), TRY_CAST(结束时间 AS DATETIME)),
        @结束时间 = TRY_CAST(结束时间 AS DATETIME),
        @当日班次最小标准工时 = ISNULL(当日班次最小标准工时, 8),
        @班次标准工时 = ISNULL(班次标准工时, 8),
        @班次 = 班次
    FROM View_生产工时视图
    WHERE AID = @RecordAID;
    
    -- 如果开始时间为空，使用当前时间
    IF @开始时间 IS NULL
        SET @开始时间 = GETDATE();
    
    -- 如果结束时间为空，使用开始时间
    IF @结束时间 IS NULL
        SET @结束时间 = @开始时间;
    
    -- ========== 只有总时长 = 0 时才跳过SAP ==========
    IF @总时长 = 0
    BEGIN
        SET @UploadMinutes = 0;
        SET @WorkType = '跳过SAP';
        SET @CalculationDetail = (
            SELECT 
                @RecordAID AS RecordAID,
                @操作人 AS Operator,
                @操作类别 AS WorkCategory,
                @总时长 AS TotalSeconds,
                0 AS BaseMinutes,
                '总时长为0，跳过SAP上传，直接校验' AS Message,
                GETDATE() AS CalculateTime
            FOR JSON PATH, WITHOUT_ARRAY_WRAPPER
        );
        RETURN;
    END
    
    -- 判断工时类型（用于前端显示）
    IF @操作类别 IN ('加班', '休息日加班', '法定节假日加班')
        SET @WorkType = '加班';
    ELSE IF @操作类别 IN ('报工', '开始加工')
        SET @WorkType = '工作';
    ELSE IF @操作类别 IN ('辅助结束', '辅助开始')
        SET @WorkType = '辅助';
    ELSE
        SET @WorkType = '其他';
    
    -- 基础分钟数
    DECLARE @BaseMinutes DECIMAL(18,2) = @总时长 / 60.0;
    DECLARE @Ratio DECIMAL(18,6) = 1.0;
    DECLARE @TotalDailyMinutes DECIMAL(18,2) = 0;
    DECLARE @StandardHoursToUse DECIMAL(10,2);
    
    IF @当日班次最小标准工时 > 0
        SET @StandardHoursToUse = @当日班次最小标准工时;
    ELSE
        SET @StandardHoursToUse = @班次标准工时;
    
    -- ========== 获取班次时间（优先按人员名称，其次按工位名称） ==========
    DECLARE @班次开始时间 TIME = NULL, @班次结束时间 TIME = NULL;
    
    SELECT TOP 1 
        @班次开始时间 = 开始时间,
        @班次结束时间 = 结束时间
    FROM [YL_MESDB].[dbo].[View_设备工位人员]
    WHERE 是否删除 = 0
      AND (人员名称 = @操作人 OR 工位名称 = @工位名称)
    ORDER BY CASE WHEN 人员名称 = @操作人 THEN 1 ELSE 2 END;  -- 优先匹配人员
    
    -- 如果没找到班次，使用默认值（白班 07:45-16:30）
    IF @班次开始时间 IS NULL
        SET @班次开始时间 = '07:45';
    IF @班次结束时间 IS NULL
        SET @班次结束时间 = '16:30';
    
    PRINT 'AID ' + CAST(@RecordAID AS NVARCHAR) + ' 班次时间: ' + CAST(@班次开始时间 AS NVARCHAR) + ' - ' + CAST(@班次结束时间 AS NVARCHAR);
    
    -- ========== 计算班次内外时间 ==========
    DECLARE @班次内秒数 INT = 0, @班次外秒数 INT = 0;
    
    -- 调用函数计算班次内外时间
    EXEC usp_CalculateShiftTime 
        @开始时间 = @开始时间,
        @结束时间 = @结束时间,
        @班次开始 = @班次开始时间,
        @班次结束 = @班次结束时间,
        @班次内秒数 = @班次内秒数 OUTPUT,
        @班次外秒数 = @班次外秒数 OUTPUT;
    
    PRINT '  班次内秒数: ' + CAST(@班次内秒数 AS NVARCHAR) + ', 班次外秒数: ' + CAST(@班次外秒数 AS NVARCHAR);
    
    -- ========== 计算比例系数 ==========
    -- 只有需要乘系数的记录才计算比例系数
    DECLARE @WorkDate DATE = TRY_CAST(@开始时间 AS DATE);
    
    IF @WorkDate IS NOT NULL
    BEGIN
        EXEC usp_CalculateDailyRatio 
            @OperatorName = @操作人,
            @WorkDate = @WorkDate,
            @StandardHours = @StandardHoursToUse,
            @Ratio = @Ratio OUTPUT,
            @TotalMinutes = @TotalDailyMinutes OUTPUT;
    END
    
    PRINT '  比例系数: ' + CAST(@Ratio AS NVARCHAR) + ', 当日总分钟: ' + CAST(@TotalDailyMinutes AS NVARCHAR);
    
    -- ========== 计算最终上传工时 ==========
    DECLARE @班次内分钟 DECIMAL(18,2) = @班次内秒数 / 60.0;
    DECLARE @班次外分钟 DECIMAL(18,2) = @班次外秒数 / 60.0;
    
    IF @操作类别 IN ('休息日加班', '法定节假日加班')
    BEGIN
        -- 休息日/法定节假日加班：班次内乘系数，班次外不乘
        SET @UploadMinutes = (@班次内分钟 * @Ratio) + @班次外分钟;
        PRINT '  休息日/法定节假日加班: (' + CAST(@班次内分钟 AS NVARCHAR) + ' * ' + CAST(@Ratio AS NVARCHAR) + ') + ' + CAST(@班次外分钟 AS NVARCHAR) + ' = ' + CAST(@UploadMinutes AS NVARCHAR);
    END
    ELSE IF @操作类别 = '加班'
    BEGIN
        -- 工作日加班：全部不乘系数
        SET @UploadMinutes = @BaseMinutes;
        PRINT '  工作日加班: ' + CAST(@BaseMinutes AS NVARCHAR) + ' (不乘系数)';
    END
    ELSE
    BEGIN
        -- 正常报工/辅助：全部乘系数
        SET @UploadMinutes = @BaseMinutes * @Ratio;
        PRINT '  正常报工/辅助: ' + CAST(@BaseMinutes AS NVARCHAR) + ' * ' + CAST(@Ratio AS NVARCHAR) + ' = ' + CAST(@UploadMinutes AS NVARCHAR);
    END
    
    -- 构建计算详情
    SET @CalculationDetail = (
        SELECT 
            @RecordAID AS RecordAID,
            @操作人 AS Operator,
            @操作类别 AS WorkCategory,
            @总时长 AS TotalSeconds,
            @BaseMinutes AS BaseMinutes,
            @班次内秒数 AS ShiftSeconds,
            @班次内分钟 AS ShiftMinutes,
            @班次外秒数 AS OvertimeSeconds,
            @班次外分钟 AS OvertimeMinutes,
            @绑定设备数 AS DeviceCount,
            @StandardHoursToUse AS StandardHours,
            @TotalDailyMinutes AS DailyTotalMinutes,
            @Ratio AS Ratio,
            @UploadMinutes AS UploadMinutes,
            @WorkType AS WorkType,
            @班次开始时间 AS ShiftStart,
            @班次结束时间 AS ShiftEnd,
            GETDATE() AS CalculateTime
        FOR JSON PATH, WITHOUT_ARRAY_WRAPPER
    );
END
GO
/****** Object:  StoredProcedure [dbo].[usp_GenerateSAPDocumentLines]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- 存储过程：usp_GenerateSAPDocumentLines
-- 功能：生成完整的SAP工时单据行项目
-- =============================================
CREATE PROCEDURE [dbo].[usp_GenerateSAPDocumentLines]
    @BatchID UNIQUEIDENTIFIER = NULL,  -- 批次ID
    @SAPDocument NVARCHAR(MAX) OUTPUT  -- 输出完整SAP单据JSON
AS
BEGIN
    SET NOCOUNT ON;
    
    IF @BatchID IS NULL
        SET @BatchID = NEWID();
    
    DECLARE @DocDate DATE = CAST(GETDATE() AS DATE);
    
    -- 构建完整的SAP单据
    SET @SAPDocument = (
        SELECT 
            @DocDate AS DocDate,
            @DocDate AS DocDueDate,
            '' AS Comments,
            (
                SELECT 
                    s.上传工时 AS Quantity,
                    202 AS BaseType,
                    v.订单号 AS BaseEntry,
                    s.BaseLine,  -- 需要从SAP查询获得
                    'dlt_Resource' AS LineType,
                    '' AS WarehouseCode,
                    CASE 
                        WHEN s.工时类型 = '工作' THEN v.工位名称
                        ELSE v.操作人
                    END AS U_ResName,
                    s.工时类型 AS WorkType,
                    v.工序名称 AS ProcessName,
                    JSON_QUERY(s.计算详情) AS CalculationDetail
                FROM SAP工时待发送表 s
                INNER JOIN View_生产工时视图 v ON s.RecordAID = v.AID
                WHERE s.状态 = '待发送'
                ORDER BY v.订单号, v.工序名称
                FOR JSON PATH
            ) AS DocumentLines
        FOR JSON PATH, WITHOUT_ARRAY_WRAPPER
    );
    
    -- 更新状态为已生成
    UPDATE SAP工时待发送表 
    SET 状态 = '已生成', 
        批次ID = @BatchID,
        生成时间 = GETDATE()
    WHERE 状态 = '待发送';
    
    -- 记录批次信息
    INSERT INTO SAP发送批次记录 (批次ID, 单据内容, 记录数, 创建时间)
    SELECT 
        @BatchID,
        @SAPDocument,
        COUNT(*),
        GETDATE()
    FROM SAP工时待发送表 
    WHERE 批次ID = @BatchID;
END
GO
/****** Object:  StoredProcedure [dbo].[usp_GetAbnormalMinutesByTask]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- 存储过程：usp_GetAbnormalMinutesByTask
-- 功能：获取指定TaskAID的异常总时间
-- =============================================
CREATE PROCEDURE [dbo].[usp_GetAbnormalMinutesByTask]
    @TaskAID INT,
    @AbnormalMinutes DECIMAL(18,2) OUTPUT
AS
BEGIN
    SET NOCOUNT ON;
    
    SELECT @AbnormalMinutes = ISNULL(SUM(总时长), 0) / 60.0
    FROM View_生产工时视图
    WHERE TaskAID = @TaskAID
        AND 操作类别 = '异常'
        AND 总时长 > 0;
    
    RETURN 0;
END
GO
/****** Object:  StoredProcedure [dbo].[usp_ValidateWorkTime]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- 存储过程：usp_ValidateWorkTime
-- 功能：校验单条工时记录并生成SAP数据
-- =============================================
create PROCEDURE [dbo].[usp_ValidateWorkTime]
    @RecordAID INT,
    @Operator NVARCHAR(50),
    @Editor NVARCHAR(50),
    @StartTime DATETIME = NULL,
    @EndTime DATETIME = NULL,
    @Success BIT OUTPUT,
    @Message NVARCHAR(500) OUTPUT,
    @SAPDocumentLine NVARCHAR(MAX) OUTPUT  -- 输出SAP行项目JSON
AS
BEGIN
    SET NOCOUNT ON;
    
    BEGIN TRY
        BEGIN TRANSACTION;
        
        DECLARE @UploadMinutes DECIMAL(18,2),
                @WorkType NVARCHAR(20),
                @CalculationDetail NVARCHAR(MAX),
                @订单编号 INT,
                @工位名称 NVARCHAR(100),
                @操作人 NVARCHAR(50),
                @加工工时 DECIMAL(18,2),
                @总时长 DECIMAL(18,2),
                @工序名称 NVARCHAR(100);
        
        -- 1. 计算上传工时
        EXEC usp_CalculateUploadMinutes 
            @RecordAID = @RecordAID,
            @UploadMinutes = @UploadMinutes OUTPUT,
            @WorkType = @WorkType OUTPUT,
            @CalculationDetail = @CalculationDetail OUTPUT;
        
        -- 2. 获取记录详细信息
        SELECT 
            @订单编号 = 订单号,
            @工位名称 = 工位名称,
            @操作人 = 操作人,
            @加工工时 = ISNULL(加工工时, 0),
            @总时长 = ISNULL(总时长, 0),
            @工序名称 = 工序名称
        FROM View_生产工时视图
        WHERE AID = @RecordAID;
        
        -- 3. 校验工时有效性
        IF @UploadMinutes <= 0
        BEGIN
            SET @Success = 0;
            SET @Message = '工时计算为0或负数，无法上传';
            ROLLBACK TRANSACTION;
            RETURN;
        END
        
        -- 4. 构建SAP行项目JSON
        SET @SAPDocumentLine = (
            SELECT 
                @UploadMinutes AS Quantity,
                202 AS BaseType,
                @订单编号 AS BaseEntry,
                @工位名称 AS ResourceName,
                @操作人 AS Operator,
                @WorkType AS WorkType,
                @工序名称 AS ProcessName,
                JSON_QUERY(@CalculationDetail) AS CalculationDetail
            FOR JSON PATH, WITHOUT_ARRAY_WRAPPER
        );
        
        -- 5. 更新校验状态
        IF @StartTime IS NOT NULL AND @EndTime IS NOT NULL
        BEGIN
            UPDATE YL_加工中心_操作记录表
            SET 开始时间 = @StartTime,
                结束时间 = @EndTime,
                总时长 = DATEDIFF(SECOND, @StartTime, @EndTime),
                最后编辑人 = @Editor,
                最后编辑时间 = GETDATE()
            WHERE AID = @RecordAID;
        END
        
        -- 6. 记录到校验表
        IF NOT EXISTS (SELECT 1 FROM 生产管理_工时校验_校验工时表 WHERE 报工记录id = @RecordAID)
        BEGIN
            INSERT INTO 生产管理_工时校验_校验工时表 (
                报工记录id, 
                操作类别编号, 
                操作类别, 
                工序名称, 
                工位名称, 
                操作人, 
                订单编号,
                开始时间,
                结束时间,
                工时,
                最后编辑人,
                最后编辑时间,
                计算详情,
                上传工时,
                工时类型
            )
            SELECT 
                AID,
                操作类别编号,
                操作类别,
                工序名称,
                工位名称,
                操作人,
                订单号,
                开始时间,
                结束时间,
                加工工时,
                @Editor,
                GETDATE(),
                @CalculationDetail,
                @UploadMinutes,
                @WorkType
            FROM View_生产工时视图
            WHERE AID = @RecordAID;
        END
        ELSE
        BEGIN
            UPDATE 生产管理_工时校验_校验工时表
            SET 计算详情 = @CalculationDetail,
                上传工时 = @UploadMinutes,
                工时类型 = @WorkType,
                最后编辑人 = @Editor,
                最后编辑时间 = GETDATE()
            WHERE 报工记录id = @RecordAID;
        END
        
        COMMIT TRANSACTION;
        
        SET @Success = 1;
        SET @Message = '校验成功，上传工时：' + CAST(@UploadMinutes AS NVARCHAR(20)) + '分钟';
        
    END TRY
    BEGIN CATCH
        ROLLBACK TRANSACTION;
        SET @Success = 0;
        SET @Message = ERROR_MESSAGE();
        SET @SAPDocumentLine = NULL;
    END CATCH
END
GO
/****** Object:  StoredProcedure [dbo].[WEB_报警_记录_历史_分页查询]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[WEB_报警_记录_历史_分页查询]
@工位号 nvarchar(50) = '',
@数据名称 nvarchar(50) = '',
@开始时间 datetime = null,
@结束时间 datetime = null,
@PageCurrent 	int,       --要显示的页码
@PageSize   	int,     --每页的大小(记录数)
@PageCount  	int  output,     --总页数
@ItemCount	int  output	--数据总数


AS
BEGIN
	  SET NOCOUNT ON;
declare @tbname		sysname --要分页显示的表名
declare @fieldkey	sysname--用于定位记录的主键(惟一键)字段,只能是单个字段
declare @where		nvarchar(1000)--查询条件
declare @fieldshow	nvarchar(1000)--以逗号分隔的要显示的字段列表,如果不指定,则显示所有字段
declare @fieldOrder	nvarchar(1000) ----以逗号分隔的排序字段列表,可以指定在字段后面指定DESC/ASC  --用于指定排序顺序
--[报警1提示2] AS 报警类型
set @where =' 1=1 '
set @tbname = '[dbo].[报警_记录_历史_视图]'
set @fieldkey = 'AID_N'
set @fieldOrder= '[开始时间] DESC'
set @fieldshow='[报警内容]
      ,[开始时间]
      ,[结束时间]
      ,[持续时间]
      ,[工位号]
      ,[工位名称]'

set @where = @where + ' and convert(varchar(10),开始时间,120) between '+ ''''+convert(varchar(10), @开始时间, 120) + '''' + ' and '+ ''''+convert(varchar(10), @结束时间, 120)+ ''''

if @数据名称 != '' set @where = @where + ' and 报警内容 like '+ '''' + '%'+ @数据名称  + '%'+ ''''
if @工位号 != '' set @where = @where + ' and 工位号 = '''+@工位号+''''

exec dbo.sp_xt_pagesplit1 @tbname,@fieldkey,@where,@fieldshow,@fieldOrder,@PageCurrent,@PageSize,@PageCount out,@ItemCount out
end
GO
/****** Object:  StoredProcedure [dbo].[WEB_登录基础数据_人员信息_重置密码]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[WEB_登录基础数据_人员信息_重置密码]
@Personnel_Number int
AS 

update 登录基础数据_人员信息 set password = '123456' where [Personnel_Number] = @Personnel_Number
select 1 as result,'修改成功！' as msg
GO
/****** Object:  StoredProcedure [dbo].[YL_设备管理_工时记录_增加]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE    PROCEDURE [dbo].[YL_设备管理_工时记录_增加]
@ChangeTime datetime = null,
@TagValue int = -1,
@Zone nvarchar(50) = ''
 AS

-- 异常数据不记录
if(@TagValue < 0) return

declare @上次循环时间 int = 0
declare @订单编号 int = -9999
declare @TaskAID int = -9999
-- 查询当前设备在加工的订单
SELECT @订单编号 = [订单编号],@TaskAID = [AID] FROM  [dbo].[MES_接口_生产计划_生产任务]  where 加工状态 = 4 and 指派对象 = @Zone

-- 没有查询到订单编号，暂不记录
-- if(@订单编号 <= 0)return

select @上次循环时间 = convert(int,[TagValueOriginal]) from [CaChe_Var] where TagName = '循环时间' and [Zone] = @Zone

if(@上次循环时间 > @TagValue)
begin

insert into [YL_设备管理_工时记录] ([指派对象]
      ,[订单编号]
	  ,TaskAID
      ,[循环时间]
      ,[采集时间]) values (@Zone,@订单编号,@TaskAID,@上次循环时间,@ChangeTime)
end
GO
/****** Object:  StoredProcedure [dbo].[菜单管理_角色模块_二级_增加数据]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE      PROCEDURE [dbo].[菜单管理_角色模块_二级_增加数据]

@二级模块id组   nvarchar(4000) = null,
@角色编号  nvarchar(4000)=null,
@pid nvarchar(4000)=null

AS

 SET NOCOUNT ON

    DECLARE @Length INT
    DECLARE @第一个二级模块id   varchar(4000)
    DECLARE @二级模块id   varchar(4000)
    
	SET XACT_ABORT ON

    BEGIN TRANSACTION
	
SELECT @Length = DATALENGTH(@二级模块id组)

WHILE @Length > 0
BEGIN
	
	EXECUTE @Length = p_PopFirstWord @二级模块id组 OUTPUT, @第一个二级模块id OUTPUT
	
	IF @Length > 0
	BEGIN
		SELECT @二级模块id = CONVERT(int, @第一个二级模块id)
		

		declare @是否存在二级菜单 int = 0
		select @是否存在二级菜单=count(*) from  [dbo].[登录基础数据_二级菜单] where id = @二级模块id and 账号代码 = @角色编号 and pid = @pid 

		if @是否存在二级菜单 > 0
		begin
		update [dbo].[登录基础数据_二级菜单] set 是否启用 =1,pid = @pid  where id = @二级模块id and 账号代码 = @角色编号
		end
		else
		begin
		insert into [dbo].[登录基础数据_二级菜单] select [id],@pid,[path],[componet],[redirect],[name],[title],[icon]
			  ,@角色编号,[模块代码],GETDATE(),1,[AddData]
      ,[DeleteData]
      ,[EditData]
      ,[SearchData] FROM [dbo].[登录基础数据_二级菜单] where id = @二级模块id and 账号代码 =1
		end





	END 
END
    COMMIT TRANSACTION
 RETURN 0
--select * from 基础表_角色模块信息 inner join 基础表_模块信息 on 基础表_角色模块信息.id = 基础表_模块信息.id
GO
/****** Object:  StoredProcedure [dbo].[菜单管理_角色模块_删除数据]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO





CREATE        PROCEDURE [dbo].[菜单管理_角色模块_删除数据]
@id  int = null,
@角色编号  int
AS

delete from  [dbo].[登录基础数据_二级菜单]  where id = @id and 账号代码 = @角色编号
GO
/****** Object:  StoredProcedure [dbo].[菜单管理_角色模块_一级_增加数据]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO





CREATE        PROCEDURE [dbo].[菜单管理_角色模块_一级_增加数据]
@一级模块id组   nvarchar(4000) = null,
@角色编号  int
AS

 SET NOCOUNT ON

    DECLARE @Length INT
    DECLARE @第一个一级模块id   varchar(4000)
    DECLARE @一级模块id   varchar(4000)
    
	SET XACT_ABORT ON

    BEGIN TRANSACTION
	
SELECT @Length = DATALENGTH(@一级模块id组)

WHILE @Length > 0
BEGIN
	
	EXECUTE @Length = p_PopFirstWord @一级模块id组 OUTPUT, @第一个一级模块id OUTPUT
	SELECT @一级模块id = CONVERT(int, @第一个一级模块id)
	IF @Length > 0
	BEGIN
		declare @是否存在一级目录 int = 0
		select @是否存在一级目录=count(*) from  [dbo].[登录基础数据_二级菜单] where id = @一级模块id and 账号代码 = @角色编号

		if @是否存在一级目录 > 0
		begin
		update [dbo].[登录基础数据_二级菜单] set 是否启用 =1  where id = @一级模块id and 账号代码 = @角色编号
		end
		else
		begin
		insert into [dbo].[登录基础数据_二级菜单] select [id],[pid],[path],[componet],[redirect],[name],[title],[icon]
			  ,@角色编号,[模块代码],[操作时间],[是否启用],[AddData]
      ,[DeleteData]
      ,[EditData]
      ,[SearchData] FROM [dbo].[登录基础数据_二级菜单] where id = @一级模块id and 账号代码 =1
		end

	END 
END
    COMMIT TRANSACTION
 RETURN 0
GO
/****** Object:  StoredProcedure [dbo].[菜单模块系统_项目角色模块列表_二级_查询数据]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE        PROCEDURE [dbo].[菜单模块系统_项目角色模块列表_二级_查询数据]
@角色编号 int
AS
select * from 登录基础数据_二级菜单 where 是否启用 = 1 and 账号代码 = @角色编号 order by 模块代码
GO
/****** Object:  StoredProcedure [dbo].[菜单模块系统_用户名密码_查询数据]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE                  PROCEDURE [dbo].[菜单模块系统_用户名密码_查询数据] 
@用户名 nvarchar(50) = null,
@密码 nvarchar(50) = null
AS
select * from 登录基础数据_管理人员权限视图 where account = @用户名 and password = @密码 and Quit =0
GO
/****** Object:  StoredProcedure [dbo].[菜单系统模块_项目角色_查询数据_MESWORK]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE   PROCEDURE [dbo].[菜单系统模块_项目角色_查询数据_MESWORK] 
@角色功能 nvarchar(50) = '',
@PageCurrent 	int,       --要显示的页码
@PageSize   	int,     --每页的大小(记录数)
@PageCount  	int  output,     --总页数
@ItemCount	int  output	--数据总数

AS
SET NOCOUNT ON;

declare @tbname		sysname --要分页显示的表名
declare @fieldkey	sysname--用于定位记录的主键(惟一键)字段,只能是单个字段
declare @where		nvarchar(1000)--查询条件
declare @fieldshow	nvarchar(1000)--以逗号分隔的要显示的字段列表,如果不指定,则显示所有字段
declare @fieldOrder	nvarchar(1000) ----以逗号分隔的排序字段列表,可以指定在字段后面指定DESC/ASC  --用于指定排序顺序

set @where =' 1=1 AND Roles_number != 1  '
set @tbname = '登录基础数据_角色信息'
set @fieldkey = ' Roles_number '
set @fieldOrder= ' Roles_number '
set @fieldshow=''


set @where = @where + ' AND [Roles_Function] like  ' +'''' + '%' + @角色功能  + '%'+''''

PRINT @where
exec dbo.sp_xt_pagesplit @tbname,@fieldkey,@where,@fieldshow,@fieldOrder,@PageCurrent,@PageSize,@PageCount out,@ItemCount out

GO
/****** Object:  StoredProcedure [dbo].[菜单系统模块_项目角色_删除_MESWORK]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO






CREATE      PROCEDURE [dbo].[菜单系统模块_项目角色_删除_MESWORK]
@角色编号 int = null
AS

SET NOCOUNT ON;

begin

declare @是否分配菜单 int 
declare @是否分配人员 int 

select @是否分配菜单 = COUNT(*) from [dbo].[登录基础数据_二级菜单] where  账号代码 = @角色编号
select @是否分配人员 = COUNT(*) from [dbo].[登录基础数据_人员权限角色] where  Roles_number = @角色编号

if @是否分配菜单 > 0
	begin
		select 0 as result
		return
	end

if @是否分配人员 > 0
	begin
		select 2 as result
		return
	end

 delete from [dbo].[登录基础数据_角色信息] where Roles_number = @角色编号
 select 1 as result

end
GO
/****** Object:  StoredProcedure [dbo].[菜单系统模块_项目角色_修改数据_MESWORK]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE      PROCEDURE [dbo].[菜单系统模块_项目角色_修改数据_MESWORK]
@角色功能 nvarchar(50),
@角色编号 int = null
AS


DECLARE @同名角色是否存在 int = 0

SELECT @同名角色是否存在 = count(*) FROM [登录基础数据_角色信息] WHERE [Roles_Function] = @角色功能 AND [Roles_number] != @角色编号

if(@同名角色是否存在 = 0)
begin
UPDATE [dbo].[登录基础数据_角色信息]
SET 
[Roles_Function]=@角色功能
WHERE [Roles_number] = @角色编号
select 1 as result
end
else
begin
select 2 as result
end
GO
/****** Object:  StoredProcedure [dbo].[菜单系统模块_项目角色_增加_MESWORK]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE    PROCEDURE [dbo].[菜单系统模块_项目角色_增加_MESWORK]

@角色功能 nvarchar(50)

AS



DECLARE @同名角色是否存在 int = 0

SELECT @同名角色是否存在 = count(*) FROM [登录基础数据_角色信息] WHERE [Roles_Function] = @角色功能

if(@同名角色是否存在 = 0)
begin
INSERT INTO [dbo].[登录基础数据_角色信息]( [Roles_Function])
VALUES(@角色功能)
select 1 as result
end
else
begin
select 2 as result
end



GO
/****** Object:  StoredProcedure [dbo].[查询字典]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[查询字典]
as
SELECT * FROM [dbo].[YL_基础表_数据字典]

GO
/****** Object:  StoredProcedure [dbo].[车间生产管理工艺_零件工序_保存为标准工艺]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		张
-- Create date: 2025-09-20
-- =============================================
CREATE     PROCEDURE [dbo].[车间生产管理工艺_零件工序_保存为标准工艺]
@物料编号 nvarchar(500),
@订单编号 int
 AS
 delete 车间生产管理工艺_零件工序_工艺库 where 零件图号 = @物料编号
 insert into 车间生产管理工艺_零件工序_工艺库 ( [零件图号]
      ,[工艺编号]
      ,[工艺顺序]
      ,[工艺要求]
      ,[是否最后一序]
      ,[计划数量]
      ,[准备工时]
      ,[标准工时]
      ,[工时合计]
      ,[工卡量具]
      ,[指定机床]
      ,[车间]
	  ,[启用]) 
	  select [零件图号]
      ,[工艺编号]
      ,[工艺顺序]
      ,[工艺要求]
      ,[是否最后一序]
      ,[计划数量]
      ,[准备工时]
      ,[标准工时]
      ,[工时合计]
      ,[工卡量具]
      ,[指定机床]
      ,[车间]
	  ,1
	   from 车间生产管理工艺_零件生产工艺_工艺库 where 订单编号 = @订单编号 
update [dbo].[MES_接口_生产计划] set 标准工艺 = 1 where 物料编号=@物料编号

GO
/****** Object:  StoredProcedure [dbo].[车间生产管理工艺_零件工序_编辑_工艺库]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		刘帅
-- Create date: 2021-03-01
-- =============================================
CREATE       PROCEDURE [dbo].[车间生产管理工艺_零件工序_编辑_工艺库]
@idd int,
@工艺要求 nvarchar(500)=null,
@准备工时 int = null,
@标准工时 int = null,
@工时合计 int = null,
@工卡量具 nvarchar(500)=null,
@指定机床 nvarchar(500)=null,
@车间 nvarchar(500)=null,
@备注 nvarchar(500)=null
 AS
 update 车间生产管理工艺_零件工序_工艺库 set 工艺要求=@工艺要求,准备工时=@准备工时,标准工时 = @标准工时,工时合计=@工时合计,工卡量具=@工卡量具,指定机床=@指定机床,车间=@车间,备注=@备注 where id = @idd
GO
/****** Object:  StoredProcedure [dbo].[车间生产管理工艺_零件工序_编辑插入行]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		刘帅
-- Create date: 2021-03-01
-- =============================================
CREATE       PROCEDURE [dbo].[车间生产管理工艺_零件工序_编辑插入行]
@idd int,
@工艺编号 int,
@物料编号 nvarchar(50)
 AS
update 车间生产管理工艺_零件工序_工艺库 set 工艺编号=@工艺编号 where id = @idd

update 车间生产管理工艺_零件工序_工艺库 set 启用 = 0 where 零件图号 = @物料编号
update [dbo].[MES_接口_生产计划] set 标准工艺 = 0 where 物料编号=@物料编号
GO
/****** Object:  StoredProcedure [dbo].[车间生产管理工艺_零件工序_插入工序_工艺库]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		刘帅
-- Create date: 2021-05-06
-- =============================================
CREATE      PROCEDURE [dbo].[车间生产管理工艺_零件工序_插入工序_工艺库]
@零件图号 nvarchar(50) = null,
@idd int = null
AS


declare @工序顺序 int
select @工序顺序 = 工艺顺序 from dbo.车间生产管理工艺_零件工序_工艺库 where  id=@idd 
update dbo.车间生产管理工艺_零件工序_工艺库
set 工艺顺序 = 工艺顺序+1
where 工艺顺序>=@工序顺序 and 零件图号=@零件图号
insert dbo.车间生产管理工艺_零件工序_工艺库(零件图号,工艺顺序)values(@零件图号, @工序顺序 )
select @工序顺序

GO
/****** Object:  StoredProcedure [dbo].[车间生产管理工艺_零件工序_查询工序信息_工艺库]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		刘帅
-- Create date: 2021-03-01
-- =============================================
CREATE PROCEDURE [dbo].[车间生产管理工艺_零件工序_查询工序信息_工艺库]
@物料编号 nvarchar(50) = null
 AS

SELECT dbo.车间生产管理工艺_零件工序_工艺库.id, 
      dbo.车间生产管理工艺_零件工序_工艺库.工艺要求, 
      dbo.车间生产管理工艺_零件工序_工艺库.工艺编号, 
      dbo.基础表_工序.工序名称 as 工艺名称 ,
      dbo.车间生产管理工艺_零件工序_工艺库.工艺顺序, 
      零件图号,
	  dbo.车间生产管理工艺_零件工序_工艺库.工艺要求,
      dbo.车间生产管理工艺_零件工序_工艺库.准备工时,
      dbo.车间生产管理工艺_零件工序_工艺库.标准工时,
      dbo.车间生产管理工艺_零件工序_工艺库.工时合计,
      dbo.车间生产管理工艺_零件工序_工艺库.工卡量具,
      dbo.车间生产管理工艺_零件工序_工艺库.指定机床,
      dbo.车间生产管理工艺_零件工序_工艺库.车间,
	  dbo.车间生产管理工艺_零件工序_工艺库.启用,
	  dbo.车间生产管理工艺_零件工序_工艺库.备注
FROM 车间生产管理工艺_零件工序_工艺库 left join dbo.基础表_工序
 on 车间生产管理工艺_零件工序_工艺库.工艺编号 = dbo.基础表_工序.工艺编号

where 零件图号 = @物料编号 

order by dbo.车间生产管理工艺_零件工序_工艺库.工艺顺序

GO
/****** Object:  StoredProcedure [dbo].[车间生产管理工艺_零件工序_启用]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		刘帅
-- Create date: 2021-03-01
-- =============================================
CREATE PROCEDURE [dbo].[车间生产管理工艺_零件工序_启用]
@物料编号 nvarchar(50) = null
 AS
update 车间生产管理工艺_零件工序_工艺库 set 启用 = 1 where 零件图号 = @物料编号
update [dbo].[MES_接口_生产计划] set 标准工艺 = 1 where 物料编号=@物料编号

GO
/****** Object:  StoredProcedure [dbo].[车间生产管理工艺_零件工序_删除工序_工艺库]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		刘帅
-- Create date: 2021-05-06
-- =============================================
CREATE              PROCEDURE [dbo].[车间生产管理工艺_零件工序_删除工序_工艺库] 

@物料编号 nvarchar(50) =null,
@idd int =null

AS



		-- 零件工序顺序
		declare @工序顺序 int
		select @工序顺序=工艺顺序 from 车间生产管理工艺_零件工序_工艺库 where id=@idd

		-- 所有零件向上串一行
		update 车间生产管理工艺_零件工序_工艺库 set 工艺顺序 = 工艺顺序 - 1
		where 工艺顺序>@工序顺序 and 零件图号 = @物料编号
		-- 删除该零件
		delete from 车间生产管理工艺_零件工序_工艺库 where id=@idd
		
		update 车间生产管理工艺_零件工序_工艺库 set 启用 = 0 where 零件图号 = @物料编号
		update [dbo].[MES_接口_生产计划] set 标准工艺 = 0 where 物料编号=@物料编号
		-- 最大工序顺序
		--declare @工序顺序2 int
		--select  top 1 @工序顺序2 = 工艺顺序 from dbo.车间生产管理工艺_零件工序_工艺库
		--where  零件图号 = @零件图号 order by 工艺顺序 desc
		-- 插入一条
		--set @工序顺序2 = @工序顺序2+1
		--insert dbo.车间生产管理工艺_零件工序_工艺库(零件图号,工艺顺序)
		--values(@零件图号, @工序顺序2)
GO
/****** Object:  StoredProcedure [dbo].[车间生产管理工艺_零件工序_上移工序_工艺库]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		刘帅
-- Create date: 2021-05-06
-- =============================================
CREATE          PROCEDURE [dbo].[车间生产管理工艺_零件工序_上移工序_工艺库]

@物料编号 nvarchar(50) =null,
@idd int =null

AS


declare @工序顺序 int
declare @前idd int

select @工序顺序 = 工艺顺序 from dbo.车间生产管理工艺_零件工序_工艺库
where  id=@idd

if(@工序顺序=1)
return

select @前idd = id from dbo.车间生产管理工艺_零件工序_工艺库
where  零件图号 = @物料编号 and 工艺顺序=@工序顺序-1 

update dbo.车间生产管理工艺_零件工序_工艺库
set 工艺顺序 = @工序顺序-1
where id=@idd

update dbo.车间生产管理工艺_零件工序_工艺库
set 工艺顺序 = @工序顺序
where id=@前idd

update 车间生产管理工艺_零件工序_工艺库 set 启用 = 0 where 零件图号 = @物料编号
update [dbo].[MES_接口_生产计划] set 标准工艺 = 0 where 物料编号=@物料编号
GO
/****** Object:  StoredProcedure [dbo].[车间生产管理工艺_零件工序_下移工序_工艺库]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		刘帅
-- Create date: 2021-03-01
-- =============================================
CREATE          PROCEDURE [dbo].[车间生产管理工艺_零件工序_下移工序_工艺库]
@物料编号 nvarchar(50) =null,
@idd int =null
AS


declare @工序顺序 int
declare @后idd int

select @工序顺序 = 工艺顺序 from dbo.车间生产管理工艺_零件工序_工艺库
where  id=@idd

if(@工序顺序=30)
return

select @后idd = id from dbo.车间生产管理工艺_零件工序_工艺库
where  零件图号 = @物料编号 and 工艺顺序=@工序顺序+1 

update dbo.车间生产管理工艺_零件工序_工艺库
set 工艺顺序 = @工序顺序+1
where id=@idd

update dbo.车间生产管理工艺_零件工序_工艺库
set 工艺顺序 = @工序顺序
where id=@后idd

update 车间生产管理工艺_零件工序_工艺库 set 启用 = 0 where 零件图号 = @物料编号
update [dbo].[MES_接口_生产计划] set 标准工艺 = 0 where 物料编号=@物料编号
GO
/****** Object:  StoredProcedure [dbo].[车间生产管理工艺_零件工序_修改数据_工艺库]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		刘帅
-- Create date: 2021-05-06
-- =============================================
CREATE   PROCEDURE [dbo].[车间生产管理工艺_零件工序_修改数据_工艺库]

@物料编号 nvarchar(50)=null,
@工艺编号 int =null
as

declare @idd int = null
declare @工序顺序 int= 0
select  top 1 @工序顺序 = 工艺顺序  from 车间生产管理工艺_零件工序_工艺库 where 零件图号=@物料编号 order by  工艺顺序 desc

insert into dbo.车间生产管理工艺_零件工序_工艺库(零件图号,工艺顺序,工艺编号)values(@物料编号, @工序顺序+1 ,@工艺编号) 
update 车间生产管理工艺_零件工序_工艺库 set 工艺编号=@工艺编号 where id = @idd
update 车间生产管理工艺_零件工序_工艺库 set 启用 = 0 where 零件图号 = @物料编号


--update [dbo].[MES_接口_生产计划] set 标准工艺 = 0 where 物料编号=@物料编号
GO
/****** Object:  StoredProcedure [dbo].[登录基础数据_人员信息_登陆检查密码]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[登录基础数据_人员信息_登陆检查密码]
@Personnel_Number int
AS 
declare @password nvarchar(50)
select top 1 @password = password from 登录基础数据_人员信息 where [Personnel_Number] = @Personnel_Number
if @password = '123456'
begin
	select 2 as result,'' as msg
end
else
begin
	select 1 as result,'' as msg
end
GO
/****** Object:  StoredProcedure [dbo].[登录基础数据_人员信息_修改密码]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[登录基础数据_人员信息_修改密码]
@userId int = null,
@旧密码 nvarchar(50) = '',
@新密码1 nvarchar(50) = '',
@新密码2 nvarchar(50) = ''
AS 
if (@新密码1 != @新密码2)  begin
	select 2 as result,'两次密码不一致！' as msg
	return
end
if (@新密码1 = '')  begin
	select 2 as result,'新密码不能为空！' as msg
	return
end
DECLARE @count int
SELECT @count = count(1) FROM 登录基础数据_人员信息 WHERE [Personnel_Number] = @userId and password = @旧密码
if @count > 0 
begin
	update 登录基础数据_人员信息 set password = @新密码1 where [Personnel_Number] = @userId and password = @旧密码
	select 1 as result,'修改成功！' as msg
end
else  select 2 as result,'旧密码错误，请确认密码是否输入正确！' as msg
GO
/****** Object:  StoredProcedure [dbo].[工时统计_任务工时_查询]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[工时统计_任务工时_查询]
    @合同号 NVARCHAR(50) = NULL,
    @操作人 NVARCHAR(50) = NULL,
    @产品编码 NVARCHAR(100) = NULL,
    @工序名称 NVARCHAR(50) = NULL,
    @订单号 NVARCHAR(50) = NULL,
    @开始日期 DATE = NULL,
    @结束日期 DATE = NULL
AS
BEGIN
    SET NOCOUNT ON;

    ;WITH 任务汇总 AS (
        SELECT 
            订单合同号 AS 合同号,
            订单号,
            产品编码,
            产品名称,
            工序名称,
			操作类别,
            MAX(计划数量) AS 计划数量,
            MAX(完成数量) AS 完成数量,
            SUM(CASE WHEN 操作类别 IN ('报工', '辅助结束') THEN 操作数值 ELSE 0 END) AS 报工数量,
            CAST(SUM(总时长) / 60.0 / 60.0 AS DECIMAL(10,1)) AS 总工时小时
        FROM View_生产工时视图
        WHERE (@开始日期 IS NULL OR @开始日期 = '' OR 结束时间 >= @开始日期)
          AND (@结束日期 IS NULL OR @结束日期 = '' OR 开始时间 <= @结束日期)
          AND (@合同号 IS NULL OR @合同号 = '' OR 订单合同号 LIKE '%' + @合同号 + '%')
          AND (@操作人 IS NULL OR @操作人 = '' OR 操作人 LIKE '%' + @操作人 + '%')
          AND (@产品编码 IS NULL OR @产品编码 = '' OR 产品编码 LIKE '%' + @产品编码 + '%')
          AND (@工序名称 IS NULL OR @工序名称 = '' OR 工序名称 LIKE '%' + @工序名称 + '%')
          AND (@订单号 IS NULL OR @订单号 = '' OR 订单号 LIKE '%' + @订单号 + '%')
        GROUP BY 订单合同号, 订单号, 产品编码, 产品名称, 工序名称,操作类别
    ),
    报工明细 AS (
        SELECT 
            订单合同号 AS 合同号,
            订单号,
            产品编码,
            工序名称,
            操作人,
			操作类别,
            CASE WHEN 操作类别 IN ('报工', '辅助结束') THEN 操作数值 ELSE 0 END AS 报工数量,
            CONVERT(VARCHAR(19), 开始时间, 120) AS 开始时间,
            CONVERT(VARCHAR(19), 结束时间, 120) AS 结束时间,
            CAST(总时长 / 60.0 / 60.0 AS DECIMAL(10,2)) AS 工时小时
        FROM View_生产工时视图
        WHERE (@开始日期 IS NULL OR @开始日期 = '' OR 结束时间 >= @开始日期)
          AND (@结束日期 IS NULL OR @结束日期 = '' OR 开始时间 <= @结束日期)
          AND (@合同号 IS NULL OR @合同号 = '' OR 订单合同号 LIKE '%' + @合同号 + '%')
          AND (@操作人 IS NULL OR @操作人 = '' OR 操作人 LIKE '%' + @操作人 + '%')
          AND (@产品编码 IS NULL OR @产品编码 = '' OR 产品编码 LIKE '%' + @产品编码 + '%')
          AND (@工序名称 IS NULL OR @工序名称 = '' OR 工序名称 LIKE '%' + @工序名称 + '%')
          AND (@订单号 IS NULL OR @订单号 = '' OR 订单号 LIKE '%' + @订单号 + '%')
    )
    SELECT 
        1 AS [Level],
        ISNULL(合同号, '') AS contractNo,
        ISNULL(订单号, '') AS orderNo,
        ISNULL(产品编码, '') AS productCode,
        ISNULL(产品名称, '') AS productName,
        ISNULL(工序名称, '') AS processName,
        '' AS operator,
        CASE WHEN 计划数量 IS NULL THEN '0' WHEN 计划数量 = FLOOR(计划数量) THEN CAST(CAST(计划数量 AS INT) AS VARCHAR(20)) ELSE CAST(CAST(计划数量 AS DECIMAL(10,1)) AS VARCHAR(20)) END + '/' + 
        CASE WHEN 完成数量 IS NULL THEN '0' WHEN 完成数量 = FLOOR(完成数量) THEN CAST(CAST(完成数量 AS INT) AS VARCHAR(20)) ELSE CAST(CAST(完成数量 AS DECIMAL(10,1)) AS VARCHAR(20)) END AS qty,
        CAST(报工数量 AS VARCHAR(20)) AS reportQty,
        '' AS startTime,
        '' AS endTime,
        CAST(总工时小时 AS VARCHAR(20)) AS workHours,
		操作类别
    FROM 任务汇总

    UNION ALL

    SELECT 
        2 AS [Level],
        ISNULL(合同号, '') AS contractNo,
        ISNULL(订单号, '') AS orderNo,
        ISNULL(产品编码, '') AS productCode,
        '' AS productName,
        ISNULL(工序名称, '') AS processName,
        ISNULL(操作人, '') AS operator,
        '' AS qty,
        CAST(报工数量 AS VARCHAR(20)) AS reportQty,
        ISNULL(开始时间, '') AS startTime,
        ISNULL(结束时间, '') AS endTime,
        CAST(工时小时 AS VARCHAR(20)) AS workHours,
		操作类别
    FROM 报工明细

    ORDER BY contractNo, orderNo, productCode, processName, [Level], startTime
END
GO
/****** Object:  StoredProcedure [dbo].[工时统计_任务工时_查询_导出]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[工时统计_任务工时_查询_导出]
    @合同号 NVARCHAR(50) = NULL,
    @操作人 NVARCHAR(50) = NULL,
    @产品编码 NVARCHAR(100) = NULL,
    @工序名称 NVARCHAR(50) = NULL,
    @订单号 NVARCHAR(50) = NULL,
    @开始日期 DATE = NULL,
    @结束日期 DATE = NULL
AS
BEGIN
    SET NOCOUNT ON;

    -- 导出文件名和类型
    SELECT '任务工时统计_' + REPLACE(REPLACE(REPLACE(CONVERT(NVARCHAR(19), GETDATE(), 21), ':', ''), '-', ''), ' ', '-') AS tablename, '15' AS tabletype
    
    -- 字段宽度
    SELECT 256*20 AS 合同号, 256*12 AS 订单号, 256*40 AS 产品编码, 256*25 AS 产品名称, 256*15 AS 工序名称, 
           256*12 AS 操作人, 256*12 AS 计划数量, 256*12 AS 完成数量, 256*10 AS 报工数量, 256*20 AS 开始时间, 256*20 AS 结束时间, 256*12 AS '工时(h)'
    
    -- 是否计算列
    SELECT 0 AS 合同号, 0 AS 订单号, 0 AS 产品编码, 0 AS 产品名称, 0 AS 工序名称, 
           0 AS 操作人, 0 AS 计划数量, 0 AS 完成数量, 0 AS 报工数量, 0 AS 开始时间, 0 AS 结束时间, 0 AS '工时(h)'

    -- 导出数据：每行都填满完整信息
    SELECT 
        ISNULL(订单合同号, '') AS 合同号,
        ISNULL(订单号, '') AS 订单号,
        ISNULL(产品编码, '') AS 产品编码,
        ISNULL(产品名称, '') AS 产品名称,
        ISNULL(工序名称, '') AS 工序名称,
        ISNULL(操作人, '') AS 操作人,
        CASE WHEN 计划数量 IS NULL THEN '' WHEN 计划数量 = FLOOR(计划数量) THEN CAST(CAST(计划数量 AS INT) AS VARCHAR(20)) ELSE CAST(CAST(计划数量 AS DECIMAL(10,1)) AS VARCHAR(20)) END AS 计划数量,
        CASE WHEN 完成数量 IS NULL THEN '' WHEN 完成数量 = FLOOR(完成数量) THEN CAST(CAST(完成数量 AS INT) AS VARCHAR(20)) ELSE CAST(CAST(完成数量 AS DECIMAL(10,1)) AS VARCHAR(20)) END AS 完成数量,
        CASE WHEN 操作类别 IN ('报工', '辅助结束') THEN CAST(操作数值 AS VARCHAR(20)) ELSE '0' END AS 报工数量,
        CONVERT(VARCHAR(19), 开始时间, 120) AS 开始时间,
        CONVERT(VARCHAR(19), 结束时间, 120) AS 结束时间,
        CAST(CAST(加工工时 / 60.0 / 60.0 AS DECIMAL(10,2)) AS VARCHAR(20)) AS '工时(h)'
    FROM View_生产工时视图
    WHERE (@开始日期 IS NULL OR @开始日期 = '' OR 结束时间 >= @开始日期)
          AND (@结束日期 IS NULL OR @结束日期 = '' OR 开始时间 <= @结束日期)
      AND (@合同号 IS NULL OR @合同号 = '' OR 订单合同号 LIKE '%' + @合同号 + '%')
      AND (@操作人 IS NULL OR @操作人 = '' OR 操作人 LIKE '%' + @操作人 + '%')
      AND (@产品编码 IS NULL OR @产品编码 = '' OR 产品编码 LIKE '%' + @产品编码 + '%')
      AND (@工序名称 IS NULL OR @工序名称 = '' OR 工序名称 LIKE '%' + @工序名称 + '%')
      AND (@订单号 IS NULL OR @订单号 = '' OR 订单号 LIKE '%' + @订单号 + '%')
    ORDER BY 订单合同号, 订单号, 产品编码, 工序名称, 开始时间
END
GO
/****** Object:  StoredProcedure [dbo].[工时统计_设备工时_查询]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[工时统计_设备工时_查询]
    @合同号 NVARCHAR(50) = NULL,
    @操作人 NVARCHAR(50) = NULL,
    @产品编码 NVARCHAR(100) = NULL,
    @工序名称 NVARCHAR(50) = NULL,
    @订单号 NVARCHAR(50) = NULL,
    @开始日期 DATE = NULL,
    @结束日期 DATE = NULL
AS
BEGIN
    SET NOCOUNT ON;

    ;WITH 操作人汇总 AS (
        SELECT 
            工位名称,
            COUNT(*) AS 报工次数,
            SUM(CASE WHEN 操作类别 IN ('报工', '辅助结束') THEN 操作数值 ELSE 0 END) AS 报工数量,
            CAST(SUM(加工工时) / 60.0 / 60.0 AS DECIMAL(10,1)) AS 总工时小时
        FROM View_生产工时视图
        WHERE (@开始日期 IS NULL OR @开始日期 = '' OR 结束时间 >= @开始日期)
          AND (@结束日期 IS NULL OR @结束日期 = '' OR 开始时间 <= @结束日期)
          AND 操作人 IS NOT NULL AND 操作人 != ''
          AND (@合同号 IS NULL OR @合同号 = '' OR 订单合同号 LIKE '%' + @合同号 + '%')
          AND (@操作人 IS NULL OR @操作人 = '' OR 工位名称 LIKE '%' + @操作人 + '%')
          AND (@产品编码 IS NULL OR @产品编码 = '' OR 产品编码 LIKE '%' + @产品编码 + '%')
          AND (@工序名称 IS NULL OR @工序名称 = '' OR 工序名称 LIKE '%' + @工序名称 + '%')
          AND (@订单号 IS NULL OR @订单号 = '' OR 订单号 LIKE '%' + @订单号 + '%')
		  and isNull(阶段标识,0) = -1
        GROUP BY 工位名称
    ),
    日期汇总 AS (
        SELECT 
            工位名称,
            CONVERT(VARCHAR(10), 开始时间, 120) AS 工作日期,
            COUNT(*) AS 报工次数,
            SUM(CASE WHEN 操作类别 IN ('报工', '辅助结束') THEN 操作数值 ELSE 0 END) AS 报工数量,
            CAST(SUM(加工工时) / 60.0 / 60.0 AS DECIMAL(10,1)) AS 工时小时
        FROM View_生产工时视图
        WHERE (@开始日期 IS NULL OR @开始日期 = '' OR 结束时间 >= @开始日期)
          AND (@结束日期 IS NULL OR @结束日期 = '' OR 开始时间 <= @结束日期)
          AND 工位名称 IS NOT NULL AND 工位名称 != ''
          AND (@合同号 IS NULL OR @合同号 = '' OR 订单合同号 LIKE '%' + @合同号 + '%')
          AND (@操作人 IS NULL OR @操作人 = '' OR 工位名称 LIKE '%' + @操作人 + '%')
          AND (@产品编码 IS NULL OR @产品编码 = '' OR 产品编码 LIKE '%' + @产品编码 + '%')
          AND (@工序名称 IS NULL OR @工序名称 = '' OR 工序名称 LIKE '%' + @工序名称 + '%')
          AND (@订单号 IS NULL OR @订单号 = '' OR 订单号 LIKE '%' + @订单号 + '%')
		  and isNull(阶段标识,0) = -1
        GROUP BY 工位名称, CONVERT(VARCHAR(10), 开始时间, 120)
    ),
    报工明细 AS (
        SELECT 
            工位名称,
            CONVERT(VARCHAR(10), 开始时间, 120) AS 工作日期,
            订单合同号 AS 合同号,
            订单号,
            产品编码,
            产品名称,
            工序名称,
            CASE WHEN 操作类别 IN ('报工', '辅助结束') THEN 操作数值 ELSE 0 END AS 报工数量,
            CONVERT(VARCHAR(19), 开始时间, 120) AS 开始时间,
            CONVERT(VARCHAR(19), 结束时间, 120) AS 结束时间,
            CAST(加工工时 / 60.0 / 60.0 AS DECIMAL(10,2)) AS 工时小时
        FROM View_生产工时视图
        WHERE (@开始日期 IS NULL OR @开始日期 = '' OR 结束时间 >= @开始日期)
          AND (@结束日期 IS NULL OR @结束日期 = '' OR 开始时间 <= @结束日期)
          AND 操作人 IS NOT NULL AND 操作人 != ''
          AND (@合同号 IS NULL OR @合同号 = '' OR 订单合同号 LIKE '%' + @合同号 + '%')
          AND (@操作人 IS NULL OR @操作人 = '' OR 工位名称 LIKE '%' + @操作人 + '%')
          AND (@产品编码 IS NULL OR @产品编码 = '' OR 产品编码 LIKE '%' + @产品编码 + '%')
          AND (@工序名称 IS NULL OR @工序名称 = '' OR 工序名称 LIKE '%' + @工序名称 + '%')
          AND (@订单号 IS NULL OR @订单号 = '' OR 订单号 LIKE '%' + @订单号 + '%')
		  and isNull(阶段标识,0) = -1
    )
    SELECT 
        1 AS [Level],
        工位名称 AS operator,
        '' AS dateLabel,
        CAST(报工次数 AS VARCHAR(20)) AS reportCount,
        CAST(报工数量 AS VARCHAR(20)) AS reportQty,
        '' AS contractNo,
        '' AS orderNo,
        '' AS productCode,
        '' AS productName,
        '' AS processName,
        '' AS startTime,
        '' AS endTime,
        CAST(总工时小时 AS VARCHAR(20)) AS workHours
    FROM 操作人汇总

    UNION ALL

    SELECT 
        2 AS [Level],
        工位名称 AS operator,
        工作日期 AS dateLabel,
        CAST(报工次数 AS VARCHAR(20)) AS reportCount,
        CAST(报工数量 AS VARCHAR(20)) AS reportQty,
        '' AS contractNo,
        '' AS orderNo,
        '' AS productCode,
        '' AS productName,
        '' AS processName,
        '' AS startTime,
        '' AS endTime,
        CAST(工时小时 AS VARCHAR(20)) AS workHours
    FROM 日期汇总

    UNION ALL

    SELECT 
        3 AS [Level],
        工位名称 AS operator,
        工作日期 AS dateLabel,
        '' AS reportCount,
        CAST(报工数量 AS VARCHAR(20)) AS reportQty,
        ISNULL(合同号, '') AS contractNo,
        ISNULL(订单号, '') AS orderNo,
        ISNULL(产品编码, '') AS productCode,
        ISNULL(产品名称, '') AS productName,
        ISNULL(工序名称, '') AS processName,
        ISNULL(开始时间, '') AS startTime,
        ISNULL(结束时间, '') AS endTime,
        CAST(工时小时 AS VARCHAR(20)) AS workHours
    FROM 报工明细

    ORDER BY operator, dateLabel, [Level]
END
GO
/****** Object:  StoredProcedure [dbo].[工时统计_设备工时_查询_导出]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[工时统计_设备工时_查询_导出]
    @合同号 NVARCHAR(50) = NULL,
    @操作人 NVARCHAR(50) = NULL,
    @产品编码 NVARCHAR(100) = NULL,
    @工序名称 NVARCHAR(50) = NULL,
    @订单号 NVARCHAR(50) = NULL,
    @开始日期 DATE = NULL,
    @结束日期 DATE = NULL
AS
BEGIN
    SET NOCOUNT ON;

    -- 导出文件名和类型
    SELECT '设备工时统计_' + REPLACE(REPLACE(REPLACE(CONVERT(NVARCHAR(19), GETDATE(), 21), ':', ''), '-', ''), ' ', '-') AS tablename, '15' AS tabletype
    
    -- 字段宽度
    SELECT 256*12 AS 操作人, 256*15 AS 工作日期, 256*20 AS 合同号, 256*12 AS 订单号, 256*40 AS 产品编码, 
           256*25 AS 产品名称, 256*15 AS 工序名称, 256*10 AS 报工数量, 256*20 AS 开始时间, 256*20 AS 结束时间, 256*12 AS '工时(h)'
    
    -- 是否计算列
    SELECT 0 AS 操作人, 0 AS 工作日期, 0 AS 合同号, 0 AS 订单号, 0 AS 产品编码, 
           0 AS 产品名称, 0 AS 工序名称, 0 AS 报工数量, 0 AS 开始时间, 0 AS 结束时间, 0 AS '工时(h)'

    -- 导出数据：每行都填满完整信息
    SELECT 
        工位名称,
        CONVERT(VARCHAR(10), 开始时间, 120) AS 工作日期,
        ISNULL(订单合同号, '') AS 合同号,
        ISNULL(订单号, '') AS 订单号,
        ISNULL(产品编码, '') AS 产品编码,
        ISNULL(产品名称, '') AS 产品名称,
        ISNULL(工序名称, '') AS 工序名称,
        CASE WHEN 操作类别 IN ('报工', '辅助结束') THEN CAST(操作数值 AS VARCHAR(20)) ELSE '0' END AS 报工数量,
        CONVERT(VARCHAR(19), 开始时间, 120) AS 开始时间,
        CONVERT(VARCHAR(19), 结束时间, 120) AS 结束时间,
        CAST(CAST(加工工时 / 60.0 / 60.0 AS DECIMAL(10,2)) AS VARCHAR(20)) AS '工时(h)'
    FROM View_生产工时视图
    WHERE (@开始日期 IS NULL OR @开始日期 = '' OR 报工日期 >= @开始日期)
          AND (@结束日期 IS NULL OR @结束日期 = '' OR 报工日期 <= @结束日期)
      AND 工位名称 IS NOT NULL AND 工位名称 != ''
      AND (@合同号 IS NULL OR @合同号 = '' OR 订单合同号 LIKE '%' + @合同号 + '%')
      AND (@操作人 IS NULL OR @操作人 = '' OR 工位名称 LIKE '%' + @操作人 + '%')
      AND (@产品编码 IS NULL OR @产品编码 = '' OR 产品编码 LIKE '%' + @产品编码 + '%')
      AND (@工序名称 IS NULL OR @工序名称 = '' OR 工序名称 LIKE '%' + @工序名称 + '%')
      AND (@订单号 IS NULL OR @订单号 = '' OR 订单号 LIKE '%' + @订单号 + '%')
	  and isNull(阶段标识,0) = -1
    ORDER BY 工位名称, 开始时间
END
GO
/****** Object:  StoredProcedure [dbo].[工时统计_项目工时_查询]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[工时统计_项目工时_查询]
    @合同号 NVARCHAR(50) = NULL,
    @操作人 NVARCHAR(50) = NULL,
    @产品编码 NVARCHAR(100) = NULL,
    @工序名称 NVARCHAR(50) = NULL,
    @订单号 NVARCHAR(50) = NULL,
    @开始日期 DATE = NULL,
    @结束日期 DATE = NULL
AS
BEGIN
    SET NOCOUNT ON;

    ;WITH 订单工时汇总 AS (
        SELECT 
            v.订单合同号 AS 合同号,
            v.产品编码,
            v.产品名称,
            MAX(v.计划数量) AS 计划数量,
            MAX(v.完成数量) AS 完成数量,
            SUM(CASE WHEN v.操作类别 IN ('报工', '辅助结束') THEN v.操作数值 ELSE 0 END) AS 报工数量,
            MIN(CONVERT(VARCHAR(10), v.报工日期, 120)) AS 计划开始,
            MAX(CONVERT(VARCHAR(10), v.报工日期, 120)) AS 计划完成,
            CAST(SUM(v.加工工时) / 60.0 / 60.0 AS DECIMAL(10,1)) AS 总工时小时
        FROM View_生产工时视图 v
        WHERE (@开始日期 IS NULL OR @开始日期 = '' OR 结束时间 >= @开始日期)
          AND (@结束日期 IS NULL OR @结束日期 = '' OR 开始时间 <= @结束日期)
          AND (@合同号 IS NULL OR @合同号 = '' OR v.订单合同号 LIKE '%' + @合同号 + '%')
          AND (@操作人 IS NULL OR @操作人 = '' OR v.操作人 LIKE '%' + @操作人 + '%')
          AND (@产品编码 IS NULL OR @产品编码 = '' OR v.产品编码 LIKE '%' + @产品编码 + '%')
          AND (@工序名称 IS NULL OR @工序名称 = '' OR v.工序名称 LIKE '%' + @工序名称 + '%')
          AND (@订单号 IS NULL OR @订单号 = '' OR v.订单号 LIKE '%' + @订单号 + '%')
        GROUP BY v.订单合同号, v.产品编码, v.产品名称
    ),
    工序工时明细 AS (
        SELECT 
            v.订单合同号 AS 合同号,
            v.产品编码,
            v.工序名称,
            v.操作人,
			v.订单号,
            SUM(CASE WHEN v.操作类别 IN ('报工', '辅助结束') THEN v.操作数值 ELSE 0 END) AS 报工数量,
            CAST(SUM(v.加工工时) / 60.0 / 60.0 AS DECIMAL(10,1)) AS 工时小时,
            MIN(CONVERT(VARCHAR(10), v.报工日期, 120)) AS 计划开始,
            MAX(CONVERT(VARCHAR(10), v.报工日期, 120)) AS 计划完成
        FROM View_生产工时视图 v
        WHERE (@开始日期 IS NULL OR @开始日期 = '' OR 结束时间 >= @开始日期)
          AND (@结束日期 IS NULL OR @结束日期 = '' OR 开始时间 <= @结束日期)
          AND (@合同号 IS NULL OR @合同号 = '' OR v.订单合同号 LIKE '%' + @合同号 + '%')
          AND (@操作人 IS NULL OR @操作人 = '' OR v.操作人 LIKE '%' + @操作人 + '%')
          AND (@产品编码 IS NULL OR @产品编码 = '' OR v.产品编码 LIKE '%' + @产品编码 + '%')
          AND (@工序名称 IS NULL OR @工序名称 = '' OR v.工序名称 LIKE '%' + @工序名称 + '%')
          AND (@订单号 IS NULL OR @订单号 = '' OR v.订单号 LIKE '%' + @订单号 + '%')
        GROUP BY v.订单合同号, v.产品编码, v.工序名称, v.操作人,v.订单号
    )
    SELECT 
        1 AS [Level],
        合同号 AS contractNo,
        产品名称 AS materialDesc,
        产品编码 AS materialCode,
        '' AS processName,
        '' AS operator,
        CASE WHEN 计划数量 = FLOOR(计划数量) THEN CAST(CAST(计划数量 AS INT) AS VARCHAR(20)) ELSE CAST(CAST(计划数量 AS DECIMAL(10,1)) AS VARCHAR(20)) END + '/' + 
        CASE WHEN 完成数量 = FLOOR(完成数量) THEN CAST(CAST(完成数量 AS INT) AS VARCHAR(20)) ELSE CAST(CAST(完成数量 AS DECIMAL(10,1)) AS VARCHAR(20)) END AS qty,
        CAST(报工数量 AS VARCHAR(20)) AS reportQty,
        ISNULL(计划开始, '') AS planStart,
        ISNULL(计划完成, '') AS planEnd,
        CAST(总工时小时 AS VARCHAR(20)) AS workHours,
		'' AS 订单号
    FROM 订单工时汇总
    
    UNION ALL
    
    SELECT 
        2 AS [Level],
        d.合同号 AS contractNo,
        '' AS materialDesc,
        d.产品编码 AS materialCode,
        d.工序名称 AS processName,
        d.操作人 AS operator,
        '' AS qty,
        CAST(d.报工数量 AS VARCHAR(20)) AS reportQty,
        d.计划开始 AS planStart,
        d.计划完成 AS planEnd,
        CAST(d.工时小时 AS VARCHAR(20)) AS workHours,
		d.订单号 AS 订单号
    FROM 工序工时明细 d
    
    ORDER BY contractNo, materialCode, [Level], processName
END
GO
/****** Object:  StoredProcedure [dbo].[工时统计_项目工时_查询_导出]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[工时统计_项目工时_查询_导出]
    @合同号 NVARCHAR(50) = NULL,
    @操作人 NVARCHAR(50) = NULL,
    @产品编码 NVARCHAR(100) = NULL,
    @工序名称 NVARCHAR(50) = NULL,
    @订单号 NVARCHAR(50) = NULL,
    @开始日期 DATE = NULL,
    @结束日期 DATE = NULL
AS
BEGIN
    SET NOCOUNT ON;

    -- 导出文件名和类型
    SELECT '项目工时统计_' + REPLACE(REPLACE(REPLACE(CONVERT(NVARCHAR(19), GETDATE(), 21), ':', ''), '-', ''), ' ', '-') AS tablename, '15' AS tabletype
    
    -- 字段宽度
    SELECT 256*20 AS 合同号, 256*20 AS 订单号,256*30 AS 产品名称, 256*40 AS 产品编码, 256*15 AS 工序名称, 256*12 AS 操作人, 
           256*12 AS 计划数量, 256*12 AS 完成数量, 256*10 AS 报工数量, 256*15 AS 计划开始, 256*15 AS 计划完成, 256*12 AS '工时(h)'
    
    -- 是否计算列
    SELECT 0 AS 合同号, 0 AS 订单号,0 AS 产品名称, 0 AS 产品编码, 0 AS 工序名称, 0 AS 操作人, 
           0 AS 计划数量, 0 AS 完成数量, 0 AS 报工数量, 0 AS 计划开始, 0 AS 计划完成, 0 AS '工时(h)'

    -- 导出数据：每行都填满完整信息
    SELECT 
        v.订单合同号 AS 合同号,
		v.订单号,
        v.产品名称,
        v.产品编码,
        v.工序名称,
        v.操作人,
        CASE WHEN v.计划数量 IS NULL THEN '' WHEN v.计划数量 = FLOOR(v.计划数量) THEN CAST(CAST(v.计划数量 AS INT) AS VARCHAR(20)) ELSE CAST(CAST(v.计划数量 AS DECIMAL(10,1)) AS VARCHAR(20)) END AS 计划数量,
        CASE WHEN v.完成数量 IS NULL THEN '' WHEN v.完成数量 = FLOOR(v.完成数量) THEN CAST(CAST(v.完成数量 AS INT) AS VARCHAR(20)) ELSE CAST(CAST(v.完成数量 AS DECIMAL(10,1)) AS VARCHAR(20)) END AS 完成数量,
        CASE WHEN v.操作类别 IN ('报工', '辅助结束') THEN CAST(v.操作数值 AS VARCHAR(20)) ELSE '0' END AS 报工数量,
        CONVERT(VARCHAR(10), v.报工日期, 120) AS 计划开始,
        CONVERT(VARCHAR(10), v.报工日期, 120) AS 计划完成,
        CAST(CAST(v.加工工时 / 60.0 / 60.0 AS DECIMAL(10,2)) AS VARCHAR(20)) AS '工时(h)'
    FROM View_生产工时视图 v
    WHERE(@开始日期 IS NULL OR @开始日期 = '' OR 结束时间 >= @开始日期)
          AND (@结束日期 IS NULL OR @结束日期 = '' OR 开始时间 <= @结束日期)
      AND (@合同号 IS NULL OR @合同号 = '' OR v.订单合同号 LIKE '%' + @合同号 + '%')
      AND (@操作人 IS NULL OR @操作人 = '' OR v.操作人 LIKE '%' + @操作人 + '%')
      AND (@产品编码 IS NULL OR @产品编码 = '' OR v.产品编码 LIKE '%' + @产品编码 + '%')
      AND (@工序名称 IS NULL OR @工序名称 = '' OR v.工序名称 LIKE '%' + @工序名称 + '%')
      AND (@订单号 IS NULL OR @订单号 = '' OR v.订单号 LIKE '%' + @订单号 + '%')
    ORDER BY v.订单合同号, v.产品编码, v.工序名称, v.操作人,v.订单号
END
GO
/****** Object:  StoredProcedure [dbo].[工时统计_作业者工时_查询]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[工时统计_作业者工时_查询]
    @合同号 NVARCHAR(50) = NULL,
    @操作人 NVARCHAR(50) = NULL,
    @产品编码 NVARCHAR(100) = NULL,
    @工序名称 NVARCHAR(50) = NULL,
    @订单号 NVARCHAR(50) = NULL,
    @开始日期 DATE = NULL,
    @结束日期 DATE = NULL
AS
BEGIN
    SET NOCOUNT ON;

    ;WITH 操作人汇总 AS (
        SELECT 
            操作人,
            COUNT(*) AS 报工次数,
            SUM(CASE 
                --WHEN 操作类别 IN ('报工', '辅助结束', '加班', '开始加工') THEN 操作数值 
				WHEN 操作类别 NOT IN ('异常') THEN 操作数值
                WHEN 操作类别 = '异常' THEN -操作数值  -- 异常工时记为负数
                ELSE 0 
            END) AS 报工数量,
            CAST(SUM(CASE 
                WHEN 操作类别 = '异常' THEN -总时长  -- 异常时长记为负数
                ELSE 总时长 
            END) / 60.0 / 60.0 AS DECIMAL(10,1)) AS 总工时小时
        FROM [dbo].[View_生产工时视图]
        WHERE (@开始日期 IS NULL OR @开始日期 = '' OR 开始时间 >= @开始日期)
          AND (@结束日期 IS NULL OR @结束日期 = '' OR 结束时间 <= @结束日期)
          AND 操作人 IS NOT NULL AND 操作人 != ''
          AND (@合同号 IS NULL OR @合同号 = '' OR 订单合同号 LIKE '%' + @合同号 + '%')
          AND (@操作人 IS NULL OR @操作人 = '' OR 操作人 LIKE '%' + @操作人 + '%')
          AND (@产品编码 IS NULL OR @产品编码 = '' OR 产品编码 LIKE '%' + @产品编码 + '%')
          AND (@工序名称 IS NULL OR @工序名称 = '' OR 工序名称 LIKE '%' + @工序名称 + '%')
          AND (@订单号 IS NULL OR @订单号 = '' OR 订单号 LIKE '%' + @订单号 + '%')
		  and isNull(阶段标识,0) != -1
        GROUP BY 操作人
    ),
    日期汇总 AS (
        SELECT 
            操作人,
            CONVERT(VARCHAR(10), 开始时间, 120) AS 工作日期,
            COUNT(*) AS 报工次数,
            SUM(CASE 
                --WHEN 操作类别 IN ('报工', '辅助结束', '加班', '开始加工') THEN 操作数值 
				WHEN 操作类别 NOT IN ('异常') THEN 操作数值
                WHEN 操作类别 = '异常' THEN -操作数值  -- 异常工时记为负数
                ELSE 0 
            END) AS 报工数量,
            CAST(SUM(CASE 
                WHEN 操作类别 = '异常' THEN -总时长  -- 异常时长记为负数
                ELSE 总时长 
            END) / 60.0 / 60.0 AS DECIMAL(10,1)) AS 工时小时
        FROM [dbo].[View_生产工时视图]
        WHERE (@开始日期 IS NULL OR @开始日期 = '' OR 开始时间 >= @开始日期)
          AND (@结束日期 IS NULL OR @结束日期 = '' OR 结束时间 <= @结束日期)
          AND 操作人 IS NOT NULL AND 操作人 != ''
          AND (@合同号 IS NULL OR @合同号 = '' OR 订单合同号 LIKE '%' + @合同号 + '%')
          AND (@操作人 IS NULL OR @操作人 = '' OR 操作人 LIKE '%' + @操作人 + '%')
          AND (@产品编码 IS NULL OR @产品编码 = '' OR 产品编码 LIKE '%' + @产品编码 + '%')
          AND (@工序名称 IS NULL OR @工序名称 = '' OR 工序名称 LIKE '%' + @工序名称 + '%')
          AND (@订单号 IS NULL OR @订单号 = '' OR 订单号 LIKE '%' + @订单号 + '%')
		  and isNull(阶段标识,0) != -1
        GROUP BY 操作人, CONVERT(VARCHAR(10), 开始时间, 120)
    ),
    报工明细 AS (
        SELECT 
            操作人,
            CONVERT(VARCHAR(10), 开始时间, 120) AS 工作日期,
            订单合同号 AS 合同号,
            订单号,
            产品编码,
            产品名称,
            工序名称,
            CASE 
                --WHEN 操作类别 IN ('报工', '辅助结束', '加班', '开始加工') THEN 操作数值 
				WHEN 操作类别 NOT IN ('异常') THEN 操作数值
                WHEN 操作类别 = '异常' THEN -操作数值  -- 异常数量记为负数
                ELSE 0 
            END AS 报工数量,
            CONVERT(VARCHAR(19), 开始时间, 120) AS 开始时间,
            CONVERT(VARCHAR(19), 结束时间, 120) AS 结束时间,
            CAST(CASE 
                WHEN 操作类别 = '异常' THEN -总时长  -- 异常时长记为负数
                ELSE 总时长 
            END / 60.0 / 60.0 AS DECIMAL(10,2)) AS 工时小时,
			异常说明,
			工序说明,
			操作类别
        FROM [dbo].[View_生产工时视图]
        WHERE (@开始日期 IS NULL OR @开始日期 = '' OR 开始时间 >= @开始日期)
          AND (@结束日期 IS NULL OR @结束日期 = '' OR 结束时间 <= @结束日期)
          AND 操作人 IS NOT NULL AND 操作人 != ''
          AND (@合同号 IS NULL OR @合同号 = '' OR 订单合同号 LIKE '%' + @合同号 + '%')
          AND (@操作人 IS NULL OR @操作人 = '' OR 操作人 LIKE '%' + @操作人 + '%')
          AND (@产品编码 IS NULL OR @产品编码 = '' OR 产品编码 LIKE '%' + @产品编码 + '%')
          AND (@工序名称 IS NULL OR @工序名称 = '' OR 工序名称 LIKE '%' + @工序名称 + '%')
          AND (@订单号 IS NULL OR @订单号 = '' OR 订单号 LIKE '%' + @订单号 + '%')
		  and isNull(阶段标识,0) != -1
    )
    SELECT 
        1 AS [Level],
        操作人 AS operator,
        '' AS dateLabel,
        CAST(报工次数 AS VARCHAR(20)) AS reportCount,
        CAST(报工数量 AS VARCHAR(20)) AS reportQty,
        '' AS contractNo,
        '' AS orderNo,
        '' AS productCode,
        '' AS productName,
        '' AS processName,
        '' AS startTime,
        '' AS endTime,
		'' AS 异常说明,
        '' AS 工序说明,
		'' AS 操作类别,
        CAST(总工时小时 AS VARCHAR(20)) AS workHours
    FROM 操作人汇总

    UNION ALL

    SELECT 
        2 AS [Level],
        操作人 AS operator,
        工作日期 AS dateLabel,
        CAST(报工次数 AS VARCHAR(20)) AS reportCount,
        CAST(报工数量 AS VARCHAR(20)) AS reportQty,
        '' AS contractNo,
        '' AS orderNo,
        '' AS productCode,
        '' AS productName,
        '' AS processName,
        '' AS startTime,
        '' AS endTime,
		'' AS 异常说明,
        '' AS 工序说明,
		'' AS 操作类别,
        CAST(工时小时 AS VARCHAR(20)) AS workHours
    FROM 日期汇总

    UNION ALL

    SELECT 
        3 AS [Level],
        操作人 AS operator,
        工作日期 AS dateLabel,
        '' AS reportCount,
        CAST(报工数量 AS VARCHAR(20)) AS reportQty,
        ISNULL(合同号, '') AS contractNo,
        ISNULL(订单号, '') AS orderNo,
        ISNULL(产品编码, '') AS productCode,
        ISNULL(产品名称, '') AS productName,
        ISNULL(工序名称, '') AS processName,
        ISNULL(开始时间, '') AS startTime,
        ISNULL(结束时间, '') AS endTime,
		ISNULL(异常说明, '') AS 异常说明,
        ISNULL(工序说明, '') AS 工序说明,
		ISNULL(操作类别, '') AS 操作类别,
        CAST(工时小时 AS VARCHAR(20)) AS workHours
    FROM 报工明细

    ORDER BY operator, dateLabel, [Level]
END
GO
/****** Object:  StoredProcedure [dbo].[工时统计_作业者工时_查询_导出]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[工时统计_作业者工时_查询_导出]
    @合同号 NVARCHAR(50) = NULL,
    @操作人 NVARCHAR(50) = NULL,
    @产品编码 NVARCHAR(100) = NULL,
    @工序名称 NVARCHAR(50) = NULL,
    @订单号 NVARCHAR(50) = NULL,
    @开始日期 DATE = NULL,
    @结束日期 DATE = NULL
AS
BEGIN
    SET NOCOUNT ON;

    -- 导出文件名和类型
    SELECT '作业者工时统计_' + REPLACE(REPLACE(REPLACE(CONVERT(NVARCHAR(19), GETDATE(), 21), ':', ''), '-', ''), ' ', '-') AS tablename, '15' AS tabletype
    
    -- 字段宽度
    SELECT 256*12 AS 操作人, 256*15 AS 工作日期, 256*20 AS 合同号, 256*12 AS 订单号, 256*40 AS 产品编码, 
           256*25 AS 产品名称, 256*15 AS 工序名称, 256*10 AS 报工数量, 256*20 AS 开始时间, 256*20 AS 结束时间, 256*12 AS '工时(h)'
    
    -- 是否计算列
    SELECT 0 AS 操作人, 0 AS 工作日期, 0 AS 合同号, 0 AS 订单号, 0 AS 产品编码, 
           0 AS 产品名称, 0 AS 工序名称, 0 AS 报工数量, 0 AS 开始时间, 0 AS 结束时间, 0 AS '工时(h)'

    -- 导出数据：每行都填满完整信息
    SELECT 
        操作人,
        CONVERT(VARCHAR(10), 开始时间, 120) AS 工作日期,
        ISNULL(订单合同号, '') AS 合同号,
        ISNULL(订单号, '') AS 订单号,
        ISNULL(产品编码, '') AS 产品编码,
        ISNULL(产品名称, '') AS 产品名称,
        ISNULL(工序名称, '') AS 工序名称,
        CASE WHEN 操作类别 IN ('报工', '辅助结束','加班','异常','开始加工') THEN CAST(操作数值 AS VARCHAR(20)) ELSE '0' END AS 报工数量,
        CONVERT(VARCHAR(19), 开始时间, 120) AS 开始时间,
        CONVERT(VARCHAR(19), 结束时间, 120) AS 结束时间,
        CAST(CAST(总时长 / 60.0 / 60.0 AS DECIMAL(10,2)) AS VARCHAR(20)) AS '工时(h)'
    FROM [dbo].[View_生产工时视图]
    WHERE (@开始日期 IS NULL OR @开始日期 = '' OR 结束时间 >= @开始日期)
          AND (@结束日期 IS NULL OR @结束日期 = '' OR 开始时间 <= @结束日期)
      AND 操作人 IS NOT NULL AND 操作人 != ''
      AND (@合同号 IS NULL OR @合同号 = '' OR 订单合同号 LIKE '%' + @合同号 + '%')
      AND (@操作人 IS NULL OR @操作人 = '' OR 操作人 LIKE '%' + @操作人 + '%')
      AND (@产品编码 IS NULL OR @产品编码 = '' OR 产品编码 LIKE '%' + @产品编码 + '%')
      AND (@工序名称 IS NULL OR @工序名称 = '' OR 工序名称 LIKE '%' + @工序名称 + '%')
      AND (@订单号 IS NULL OR @订单号 = '' OR 订单号 LIKE '%' + @订单号 + '%')
	  and isNull(阶段标识,0) != -1
    ORDER BY 操作人, 开始时间
END
GO
/****** Object:  StoredProcedure [dbo].[工时校验_保存校验记录]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- 工时校验_保存校验记录
CREATE PROCEDURE [dbo].[工时校验_保存校验记录]
    @orderAID bigint,
    @开始时间 datetime,
    @结束时间 datetime,
	@总时长 int,
    @操作人 nvarchar(50),
    @最后编辑人 nvarchar(50),
	@当日班次最小标准工时 nvarchar(50)
AS
BEGIN
    SET NOCOUNT ON;
    
    BEGIN TRY
        BEGIN TRANSACTION;
        
        -- 从原表获取基础信息
        DECLARE @操作类别编号 int, @操作类别 nvarchar(50), @阶段标识 int,
                @工序名称 nvarchar(50), @工位编号 nvarchar(50), @工位名称 nvarchar(50),
                @合同号 nvarchar(50), @订单编号 nvarchar(50), @物料编号 nvarchar(50),
                @物料描述 nvarchar(50), @操作数值 int, @操作内容 nvarchar(500),
                @操作描述 nvarchar(2000), @不装配 nvarchar(50) , @AID int,@TaskAID int ;
        
        SELECT 
            @操作类别编号 = 操作类别编号,
            @操作类别 = 操作类别,
            @阶段标识 = 阶段标识,
            @工序名称 = 工序名称,
            @工位编号 = 工位编号,
            @工位名称 = 工位名称,
            @合同号 = 合同号,
            @订单编号 = 订单编号,
            @物料编号 = 物料编号,
            @物料描述 = 物料描述,
            @操作数值 = 操作数值,
            @操作内容 = 操作内容,
            @操作描述 = 操作描述,
            @不装配 = 不装配,
			@AID = AID,
			@TaskAID = TaskAID,
			@操作人 = 操作人
        FROM [dbo].[YL_加工中心_操作记录表] 
        WHERE AID = @orderAID;
        
        -- 插入校验表
        --INSERT INTO [dbo].[生产管理_工时校验_校验工时表] (
        --    操作类别编号, 操作类别, 阶段标识, 工序名称, 工位编号, 工位名称,
        --    操作人, 合同号, 订单编号, 物料编号, 物料描述, 操作数值, 操作内容,
        --    操作描述, 报工记录id,TaskAID, 开始时间, 结束时间, 工时, 报工日期, 已报工, 不装配,
        --    最后编辑人, 最后编辑时间
        --) VALUES (
        --    @操作类别编号, @操作类别, @阶段标识, @工序名称, @工位编号, @工位名称,
        --    @操作人, @合同号, @订单编号, @物料编号, @物料描述, @操作数值, @操作内容,
        --    @操作描述,@AID, @TaskAID, @开始时间, @结束时间, @工时, 
        --    CONVERT(date, GETDATE()), 1, @不装配,
        --    @最后编辑人, GETDATE()
        --);
		-- 插入校验表
        UPDATE [dbo].[YL_加工中心_操作记录表]
		SET 
			操作类别编号 = @操作类别编号,
			操作类别 = @操作类别,
			阶段标识 = @阶段标识,
			工序名称 = @工序名称,
			工位编号 = @工位编号,
			工位名称 = @工位名称,
			操作人 = @操作人,
			合同号 = @合同号,
			订单编号 = @订单编号,
			物料编号 = @物料编号,
			物料描述 = @物料描述,
			操作数值 = @操作数值,
			操作内容 = @操作内容,
			操作描述 = @操作描述,
			TaskAID = @TaskAID,
			开始时间 = @开始时间,
			结束时间 = @结束时间,
			总时长 = @总时长,
			已报工 = 1,
			不装配 = @不装配,
			最后编辑人 = @最后编辑人,
			最后编辑时间 = GETDATE(),
			班次标准工时 = @当日班次最小标准工时
		WHERE AID = @orderAID  -- 这里需要指定更新哪条记录的条件
        
        COMMIT TRANSACTION;
        
        SELECT '成功' as 结果, '校验记录保存成功' as 消息;
        
    END TRY
    BEGIN CATCH
        ROLLBACK TRANSACTION;
        SELECT '错误' as 结果, ERROR_MESSAGE() as 消息;
    END CATCH
END
GO
/****** Object:  StoredProcedure [dbo].[工时校验_获取操作记录列表]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- 工时校验_获取操作记录列表
CREATE PROCEDURE [dbo].[工时校验_获取操作记录列表]
    @开始时间 datetime = NULL,
    --@结束时间 datetime = NULL,
    @校验状态 nvarchar(4000) = 2,  -- 0:未校验, 1:已校验, 2:全部
    @过滤性质 nvarchar(4000) = 0,   -- 0:全部, 1:不包含装配, 2:包含装配
	@PageCurrent 	int=1,             --要显示的页码
	@PageSize   	int  = 20,         --每页的大小(记录数)
	@PageCount  	int OUTPUT,        --总页数
	@ItemCount	    int OUTPUT,	       --数据总数
    @异常 nvarchar(4000) = 0 ,-- 0:全部, 1:异常, 2:正常
	@任务ID nvarchar(4000) = 0, 
    @生产订单 nvarchar(4000) = 0,
	@加班 nvarchar(4000) = 0 ,-- 0:全部, 1:加班, 2:不加班
	@人员 nvarchar(4000) = 0
AS
BEGIN
    SET NOCOUNT ON;
	declare @tbname		sysname --要分页显示的表名
	declare @fieldkey	sysname --用于定位记录的主键(惟一键)字段,只能是单个字段
	declare @where		nvarchar(4000)	--查询条件
	declare @fieldshow	nvarchar(1000) --以逗号分隔的要显示的字段列表,如果不指定,则显示所有字段
	declare @fieldOrder	nvarchar(1000) ----以逗号分隔的排序字段列表,可以指定在字段后面指定DESC/ASC  --用于指定排序顺序
	
	set @tbname = ' [dbo].[View_生产工时视图] '
	set @fieldkey = ' AID '
	
	-- 构建WHERE条件
	set @where = ' (1=1) '
	
	-- 校验状态过滤
	IF @校验状态 = '0'
		set @where = @where + ' AND Expr1 IS NULL '
	ELSE IF @校验状态 = '1'
		set @where = @where + ' AND Expr1 IS NOT NULL '
	
	-- 工位名称过滤
	IF @过滤性质 = '1'
		set @where = @where + ' AND ISNULL(工位名称, '''') NOT LIKE ''%装配%'' '
	ELSE IF @过滤性质 = '2'
		set @where = @where + ' AND ISNULL(工位名称, '''') LIKE ''%装配%'' '
	
	-- 异常状态过滤
	IF @异常 = '1'
		set @where = @where + ' AND 结束时间 IS NULL '
	ELSE IF @异常 = '2'
		set @where = @where + ' AND 结束时间 IS NOT NULL  AND ISNULL(加工工时, 总时长) < 33000 AND 结束时间 > DATEADD(day, -1, GETDATE()) '
	ELSE IF @异常 = '3'
		set @where = @where + ' AND ISNULL(加工工时, 总时长) > 33000 '
	ELSE IF @异常 = '4'
		set @where = @where + ' AND 结束时间 < DATEADD(day, -1, GETDATE()) '

	IF @加班 = '1'
		set @where = @where + ' AND ISNULL(操作类别, '''')  LIKE ''%加班%''  '
	ELSE IF @加班 = '2'
		set @where = @where + ' AND ISNULL(操作类别, '''') NOT LIKE ''%加班%'' '
	-- 任务ID过滤
	IF @任务ID != '0' AND @任务ID != ''
		set @where = @where + ' AND ISNULL(AID, 0) = ' + @任务ID + ' '
	
	-- 生产订单过滤
	IF @生产订单 != '0' AND @生产订单 != ''
		set @where = @where + ' AND ISNULL(订单编号, 0) = ' + @生产订单 + ' '
	
	-- 人员过滤
	IF @人员 != '0' AND @人员 != ''
		set @where = @where + ' AND 操作人 LIKE ''%' + @人员 + '%'' '
	
	-- 时间过滤
	IF @开始时间 IS NOT NULL
		set @where = @where + ' AND 开始时间 > ''' + CONVERT(nvarchar(30), @开始时间, 120) + ''' '
	
	set @fieldOrder = ' 开始时间 DESC '
	
	print @where
	
	set @fieldshow ='
				AID
				,操作类别编号
				,操作类别
				,阶段标识
				,工序名称
				,工位编号
				,工位名称
				,操作人
				,合同号
				,订单号 as 订单编号
				,产品编码
				,产品名称
				,操作数值
				,操作内容
				,操作描述
				,TaskAID
				,开始时间
				,结束时间
				,加工工时
				,总时长
				,报工日期
				,已报工
				,不装配
				,已校验
				,最后编辑人
				,最后编辑时间 '
				
	exec [dbo].[sp_xt_pagesplit] @tbname,@fieldkey,@where,@fieldshow,@fieldOrder,@PageCurrent,@PageSize,@PageCount out,@ItemCount out

END
GO
/****** Object:  StoredProcedure [dbo].[工时校验_获取操作人当天报工记录]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[工时校验_获取操作人当天报工记录]
    @操作人 nvarchar(50),
    @开始时间 datetime,
    @结束时间 datetime
AS
BEGIN
    SELECT *
    FROM [dbo].[YL_加工中心_操作记录表]
    WHERE 操作人 = @操作人
        AND 开始时间 >= @开始时间
        AND 开始时间 <= @结束时间
        AND (总时长> 0 or 实际工时 >0)
		and isNull(阶段标识,0) != -1
		and 操作类别 not like '%加班%'
		and 订单编号 <> 3886
END
GO
/****** Object:  StoredProcedure [dbo].[工时校验_获取订单工序]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[工时校验_获取订单工序]
    @订单编号 int
AS
BEGIN
    SET NOCOUNT ON;
    
    SELECT DISTINCT 
	工序名称,订单行号 as 工艺顺序,指派对象,TaskAID,顺序编号,指派对象 as 工位名称,VisCode
    FROM [dbo].[View_生产订单_MES]
    WHERE 订单编号 = @订单编号
    ORDER BY 订单行号;
END
GO
/****** Object:  StoredProcedure [dbo].[工时校验_获取订单列表]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[工时校验_获取订单列表]
@订单编号 nvarchar(50)
AS
BEGIN
    SET NOCOUNT ON;
    
    SELECT DISTINCT top 20
        订单编号,
        物料编号 as 零件编码,
        物料描述 as 零件名称
    FROM [dbo].[MES_接口_生产计划] WHERE 订单编号 LIKE '%' + @订单编号 + '%' OR @订单编号 = ''
    ORDER BY 订单编号 ;
END
GO
/****** Object:  StoredProcedure [dbo].[工时校验_获取工序和指派对象]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[工时校验_获取工序和指派对象]
    @订单编号 int
AS
BEGIN
    SET NOCOUNT ON;
    
    select 顺序编号,指派对象,工序名称,订单行号,b.VisCode as 指派对象编号  from MES_接口_生产计划_生产任务 a left join MES_资源主数据 b on a.指派对象 = b.Name  where 订单编号 = @订单编号
END
GO
/****** Object:  StoredProcedure [dbo].[工时校验_获取设备数据]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[工时校验_获取设备数据]
    @工位名称 nvarchar(50)
AS
BEGIN
    -- 使用CTE先获取当天的数据并按时间排序
    WITH DailyData AS (
        SELECT 
            [AID],
            [工位号] AS 工位名称,
            [创建时间],
            CASE TRY_CAST([设备状态] AS INT)
                WHEN -1 THEN N'关机'
                WHEN 0 THEN N'待机'
                WHEN 1 THEN N'运行'
                WHEN 2 THEN N'报警'
                ELSE N'未知'
            END AS 设备状态,
            -- 获取下一条记录的时间来计算持续时间
            LEAD([创建时间]) OVER (ORDER BY [创建时间]) AS 下一记录时间
        FROM [dbo].[历史_工位设备状态每分钟记录]
        WHERE 工位号 = @工位名称
            AND CAST([创建时间] AS DATE) = CAST(GETDATE() AS DATE) -- 当天数据
    )
    
    -- 计算各状态的累计时间（分钟）
    SELECT 
        工位名称,
        设备状态,
        SUM(
            CASE 
                WHEN 下一记录时间 IS NOT NULL 
                THEN DATEDIFF(MINUTE, [创建时间], 下一记录时间)
                ELSE DATEDIFF(MINUTE, [创建时间], GETDATE()) -- 最后一条记录计算到当前时间
            END
        ) AS 累计分钟,
        SUM(
            CASE 
                WHEN 下一记录时间 IS NOT NULL 
                THEN DATEDIFF(SECOND, [创建时间], 下一记录时间)
                ELSE DATEDIFF(SECOND, [创建时间], GETDATE())
            END
        ) AS 累计秒数,
        -- 格式化显示为 HH:MM:SS
        RIGHT('0' + CAST(
            SUM(
                CASE 
                    WHEN 下一记录时间 IS NOT NULL 
                    THEN DATEDIFF(SECOND, [创建时间], 下一记录时间)
                    ELSE DATEDIFF(SECOND, [创建时间], GETDATE())
                END
            ) / 3600 AS VARCHAR), 2) + ':' +
        RIGHT('0' + CAST(
            (SUM(
                CASE 
                    WHEN 下一记录时间 IS NOT NULL 
                    THEN DATEDIFF(SECOND, [创建时间], 下一记录时间)
                    ELSE DATEDIFF(SECOND, [创建时间], GETDATE())
                END
            ) % 3600) / 60 AS VARCHAR), 2) + ':' +
        RIGHT('0' + CAST(
            SUM(
                CASE 
                    WHEN 下一记录时间 IS NOT NULL 
                    THEN DATEDIFF(SECOND, [创建时间], 下一记录时间)
                    ELSE DATEDIFF(SECOND, [创建时间], GETDATE())
                END
            ) % 60 AS VARCHAR), 2) AS 累计时间格式
    FROM DailyData
    WHERE 设备状态 != N'未知'
    GROUP BY 工位名称, 设备状态
    ORDER BY 设备状态
    
    -- 返回汇总统计
    SELECT 
        工位名称,
        SUM(CASE WHEN 设备状态 = N'运行' THEN 累计分钟 ELSE 0 END) AS 运行总分钟,
        SUM(CASE WHEN 设备状态 = N'待机' THEN 累计分钟 ELSE 0 END) AS 待机总分钟,
        SUM(CASE WHEN 设备状态 = N'关机' THEN 累计分钟 ELSE 0 END) AS 关机总分钟,
        SUM(CASE WHEN 设备状态 = N'报警' THEN 累计分钟 ELSE 0 END) AS 报警总分钟,
        SUM(累计分钟) AS 总记录分钟
    FROM (
        -- 子查询计算各状态累计
        SELECT 
            工位名称,
            设备状态,
            SUM(
                CASE 
                    WHEN 下一记录时间 IS NOT NULL 
                    THEN DATEDIFF(MINUTE, [创建时间], 下一记录时间)
                    ELSE DATEDIFF(MINUTE, [创建时间], GETDATE())
                END
            ) AS 累计分钟
        FROM (
            SELECT 
                [工位号] AS 工位名称,
                CASE TRY_CAST([设备状态] AS INT)
                    WHEN -1 THEN N'关机'
                    WHEN 0 THEN N'待机'
                    WHEN 1 THEN N'运行'
                    WHEN 2 THEN N'报警'
                    ELSE N'未知'
                END AS 设备状态,
                [创建时间],
                LEAD([创建时间]) OVER (ORDER BY [创建时间]) AS 下一记录时间
            FROM [dbo].[历史_工位设备状态每分钟记录]
            WHERE 工位号 = @工位名称
                AND CAST([创建时间] AS DATE) = CAST(GETDATE() AS DATE)
        ) t
        WHERE 设备状态 != N'未知'
        GROUP BY 工位名称, 设备状态
    ) t2
    GROUP BY 工位名称

END
GO
/****** Object:  StoredProcedure [dbo].[工时校验_获取新增工时任务信息]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[工时校验_获取新增工时任务信息]
@TaskAID INT
AS
BEGIN
    SET NOCOUNT ON;
    
    SELECT 工序名称,指派对象 FROM [dbo].[View_生产订单_MES] WHERE TaskAID = @TaskAID

END
GO
/****** Object:  StoredProcedure [dbo].[工时校验_获取资源]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[工时校验_获取资源]
    @资源名称 NVARCHAR(MAX) = ''
AS
BEGIN
   select VisName as  资源名称, VisCode, StdCost1 from SAP.SBO_YL.dbo.UBT_ORSC as a where a.VisName = @资源名称

END
GO
/****** Object:  StoredProcedure [dbo].[工时校验_获取昨日之前操作记录列表]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- 工时校验_获取操作记录列表
CREATE PROCEDURE [dbo].[工时校验_获取昨日之前操作记录列表]
    @开始时间 datetime = NULL,
    @结束时间 datetime = NULL,
    @校验状态 nvarchar(4000) = 2,  -- 0:未校验, 1:已校验, 2:全部
    @过滤性质 nvarchar(4000) = 0,   -- 0:全部, 1:不包含装配, 2:包含装配
	@PageCurrent 	int=1,             --要显示的页码
	@PageSize   	int  = 20,         --每页的大小(记录数)
	@PageCount  	int OUTPUT,        --总页数
	@ItemCount	    int OUTPUT,	       --数据总数
    @异常 nvarchar(4000) = 0,  -- 0:全部, 1:异常, 2:正常
	@任务ID nvarchar(4000) = 0, 
    @生产订单 nvarchar(4000) = 0,
	@加班 nvarchar(4000) = 0 ,-- 0:全部, 1:加班, 2:不加班
	@人员 nvarchar(4000) = 0

AS
BEGIN
    SET NOCOUNT ON;
	declare @tbname		sysname --要分页显示的表名
	declare @fieldkey	sysname --用于定位记录的主键(惟一键)字段,只能是单个字段
	declare @where		nvarchar(4000)	--查询条件
	declare @fieldshow	nvarchar(1000) --以逗号分隔的要显示的字段列表,如果不指定,则显示所有字段
	declare @fieldOrder	nvarchar(1000) ----以逗号分隔的排序字段列表,可以指定在字段后面指定DESC/ASC  --用于指定排序顺序
	set @tbname = ' [dbo].[View_生产工时视图] '
	set @fieldkey = ' AID '
	set @where = ' (
            '+ @校验状态 +' = 2  -- 全部
            OR ('+@校验状态+' = 0 AND Expr1 IS NULL)  -- 未校验
            OR ('+@校验状态+' = 1 AND Expr1 IS NOT NULL)  -- 已校验
        )
        -- 工位名称过滤条件（对已校验和未校验都适用）
        AND (
            '+@过滤性质+' = 0 
            OR ('+@过滤性质+' = 1 AND ISNULL(工位名称, 工位名称) NOT LIKE ''%装配%'')
            OR ('+@过滤性质+' = 2 AND ISNULL(工位名称, 工位名称) LIKE ''%装配%'')
        )
        -- 异常状态过滤条件
        AND (
            '+@异常+' = 0  -- 全部
            OR ('+@异常+' = 1 AND (ISNULL(结束时间, 结束时间) IS NULL))  -- 异常
            OR ('+@异常+' = 2 AND  ISNULL(结束时间, 结束时间) IS NOT NULL)  -- 正常
        ) 
		AND 开始时间 < CONVERT(VARCHAR(10), GETDATE(), 120) + '' 00:00:00''
		'
	IF @加班 = '1'
		set @where = @where + ' AND ISNULL(操作类别, '''')  LIKE ''%加班%''  '
	ELSE IF @加班 = '2'
		set @where = @where + ' AND ISNULL(操作类别, '''') NOT LIKE ''%加班%'' '
	-- 任务ID过滤
	IF @任务ID != '0' AND @任务ID != ''
		set @where = @where + ' AND ISNULL(AID, 0) = ' + @任务ID + ' '
	
	-- 生产订单过滤
	IF @生产订单 != '0' AND @生产订单 != ''
		set @where = @where + ' AND ISNULL(订单号, 0) = ' + @生产订单 + ' '
	
	-- 人员过滤
	IF @人员 != '0' AND @人员 != ''
		set @where = @where + ' AND 操作人 LIKE ''%' + @人员 + '%'' '
	print @where
	set @fieldOrder = ' 开始时间 DESC '
	set @fieldshow ='
				AID
				,Expr1
				,操作类别编号
				,操作类别
				,阶段标识
				,工序名称
				,工位编号
				,工位名称
				,操作人
				,合同号
				,订单号 as 订单编号
				,产品编码
				,产品名称
				,操作数值
				,操作内容
				,操作描述
				,TaskAID
				,开始时间
				,结束时间
				,加工工时
				,总时长
				,报工日期
				,已报工
				,不装配
				,已校验
				,最后编辑人
				,最后编辑时间
				,绑定设备数
				,工序说明
				,异常说明
				,当日班次最小标准工时
				,订单行号'
	exec [dbo].[sp_xt_pagesplit] @tbname,@fieldkey,@where,@fieldshow,@fieldOrder,@PageCurrent,@PageSize,@PageCount out,@ItemCount out

	
END
GO
/****** Object:  StoredProcedure [dbo].[工时校验_批量保存校验记录]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- 工时校验_保存校验记录
-- 工时校验_批量保存校验记录
CREATE PROCEDURE [dbo].[工时校验_批量保存校验记录]
    @AID列表 nvarchar(MAX),  -- 逗号分隔的AID列表
    @操作人 nvarchar(50),
    @最后编辑人 nvarchar(50)
AS
BEGIN
    SET NOCOUNT ON;
    
    BEGIN TRY
        BEGIN TRANSACTION;
        
        -- 创建临时表存储AID列表
        CREATE TABLE #TempAID (AID bigint);
        
        -- 解析AID列表
        INSERT INTO #TempAID (AID)
        SELECT value FROM STRING_SPLIT(@AID列表, ',');
        
        -- 批量插入校验表
        INSERT INTO [dbo].[生产管理_工时校验_校验工时表] (
            操作类别编号, 操作类别, 阶段标识, 工序名称, 工位编号, 工位名称,
            操作人, 合同号, 订单编号, 物料编号, 物料描述, 操作数值, 操作内容,
            操作描述, 开始时间, 结束时间, 工时, 报工日期, 已报工, 不装配,
            最后编辑人, 最后编辑时间,报工记录id,TaskAID
        )
        SELECT 
            o.操作类别编号, o.操作类别, o.阶段标识, o.工序名称, o.工位编号, o.工位名称,
            o.操作人, o.合同号, o.订单编号, o.物料编号, o.物料描述, o.操作数值, o.操作内容,
            o.操作描述, o.开始时间, o.结束时间, o.工时, 
            CONVERT(date, GETDATE()), 1, o.不装配,
            @最后编辑人, GETDATE(),o.AID,o.TaskAID
        FROM [dbo].[YL_加工中心_操作记录表] o
        INNER JOIN #TempAID t ON o.AID = t.AID
        LEFT JOIN [dbo].[生产管理_工时校验_校验工时表] c ON o.AID = c.报工记录id
        WHERE c.AID IS NULL;  -- 只插入未校验的记录
        
        DROP TABLE #TempAID;
        
        COMMIT TRANSACTION;
        
        SELECT '成功' as 结果, '批量校验记录保存成功，共处理 ' + CAST(@@ROWCOUNT as nvarchar(10)) + ' 条记录' as 消息;
        
    END TRY
    BEGIN CATCH
        ROLLBACK TRANSACTION;
        DROP TABLE IF EXISTS #TempAID;
        SELECT '错误' as 结果, ERROR_MESSAGE() as 消息;
    END CATCH
END
GO
/****** Object:  StoredProcedure [dbo].[工时校验_新增操作记录]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- 工时校验_新增操作记录（修改版）
CREATE PROCEDURE [dbo].[工时校验_新增操作记录]
    @操作类别 nvarchar(50),
    @订单编号 nvarchar(50),
    @物料编号 nvarchar(50),
    @物料描述 nvarchar(50),
    @工序名称 nvarchar(50),
    @工位名称 nvarchar(50),
    @操作人 nvarchar(50),
    @开始时间 datetime,
    @结束时间 datetime,
    @操作内容 nvarchar(500) = NULL,
    @操作描述 nvarchar(2000) = NULL,
	@TaskAID int
AS
BEGIN
    SET NOCOUNT ON;
    
    BEGIN TRY
        DECLARE @工时 int;
        
        -- 计算工时（秒）
        SET @工时 = DATEDIFF(SECOND, @开始时间, @结束时间);
        
        -- 插入操作记录表
        INSERT INTO [dbo].[YL_加工中心_操作记录表] (
            操作类别编号, 操作类别, 阶段标识, 工序名称, 工位编号, 工位名称,
            操作人, 合同号, 订单编号, 物料编号, 物料描述, 操作数值, 操作内容,
            操作描述, TaskAID, 开始时间, 结束时间, 实际工时, 报工日期, 已报工, 不装配,
            最后编辑人, 最后编辑时间
        ) VALUES (
            CASE @操作类别 
                WHEN '收料' THEN 1
                WHEN '辅助开始' THEN 2
                WHEN '辅助结束' THEN 3
                WHEN '开始加工' THEN 4
                WHEN '暂停' THEN 5
                WHEN '报工' THEN 6
                ELSE 0
            END,
            @操作类别,
            0,  -- 阶段标识
            @工序名称,
            '',  -- 工位编号
            @工位名称,
            @操作人,
            '',  -- 合同号
            @订单编号,
            @物料编号,
            @物料描述,
            0,  -- 操作数值（固定为0，已去掉该字段）
            @操作内容,
            @操作描述,
            @TaskAID,  -- TaskAID
            @开始时间,
            @结束时间,
            @工时,
            CONVERT(date, GETDATE()),
            1,  -- 已报工
            '否',  -- 不装配
            @操作人,
            GETDATE()
        );
        
        SELECT '成功' as 结果, '新增操作记录成功' as 消息, SCOPE_IDENTITY() as 新记录ID;
        
    END TRY
    BEGIN CATCH
        SELECT '错误' as 结果, ERROR_MESSAGE() as 消息, NULL as 新记录ID;
    END CATCH
END
GO
/****** Object:  StoredProcedure [dbo].[工艺管理_工艺查询]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[工艺管理_工艺查询]
@生产工艺 int,
@PageCurrent 	int=1,             --要显示的页码
@PageSize   	int  = 20,         --每页的大小(记录数)
@PageCount  	int OUTPUT,        --总页数
@ItemCount	    int OUTPUT,	       --数据总数
@物料编号 nvarchar(50)
AS
declare @tbname		sysname --要分页显示的表名
declare @fieldkey	sysname --用于定位记录的主键(惟一键)字段,只能是单个字段
declare @where		nvarchar(4000)	--查询条件
declare @fieldshow	nvarchar(1000) --以逗号分隔的要显示的字段列表,如果不指定,则显示所有字段
declare @fieldOrder	nvarchar(1000) ----以逗号分隔的排序字段列表,可以指定在字段后面指定DESC/ASC  --用于指定排序顺序
declare @GroupBy nvarchar(1000)
--SELECT [StageID] as 工艺编号 ,[StatgeName] as 工艺名称 FROM [基础表_工序] ORDER BY [StageID]

set @tbname = '[dbo].[View_标准工艺视图]'
set @fieldkey = 'id '
set @where = ' 1=1 '
set @fieldshow ='零件名称,零件图号,计划数量'
if(@物料编号<>'') set @where = @where + ' and 标准工艺 = 1 and 零件图号 = @物料编号 '
if(@物料编号 = '')set @where = @where + ' and 标准工艺 = 1 '
set @GroupBy = 'group by 零件名称,零件图号,计划数量'
--if(@生产工艺 = 1) SELECT *,[MES_接口_生产计划].物料描述 as 零件名称  FROM [车间生产管理工艺_零件生产工艺_工艺库] left join [dbo].[MES_接口_生产计划]  on  [车间生产管理工艺_零件生产工艺_工艺库].订单编号 = [MES_接口_生产计划].订单编号 where 生产工艺 = @生产工艺


exec [dbo].[sp_xt_pagesplit_group] @tbname,@fieldkey,@where,@fieldshow,@fieldOrder,@GroupBy,@PageCurrent,@PageSize,@PageCount out,@ItemCount out
GO
/****** Object:  StoredProcedure [dbo].[工艺管理_工艺查询_查询生产工艺]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[工艺管理_工艺查询_查询生产工艺]
@物料编号 nvarchar(50),
@订单编号 int 
AS
SELECT [id]
      ,[零件图号]
      ,[工艺顺序]
      ,[工艺要求]
      ,[是否最后一序]
      ,c.[订单编号]
      ,c.[计划数量]
      ,isnull(准备工时,0) as 准备工时
      ,isnull(标准工时,0) as 标准工时
      ,isnull(工时合计,0) as 工时合计
      ,[工卡量具]
      ,[指定机床]
      ,[车间]
      ,[启用]
	  ,c.工序名称 as 工艺名称 
	  ,c.合同号
	  ,c.计划完成
	  ,c.加急状态
	  ,c.物料描述 as 零件名称
	  ,c.TaskAID
	  ,c.指派对象
	  ,c.计划开始
	  ,c.计划号
	  FROM [dbo].[View_生产订单_MES] as c inner join [车间生产管理工艺_零件生产工艺_工艺库] as a   on a.订单编号 = c.订单编号 and a.工艺顺序 = c.订单行号 
	  where c.[订单编号] = @订单编号 
	  ORDER BY TaskAID 
GO
/****** Object:  StoredProcedure [dbo].[工艺管理_工艺查询_订单信息查询]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[工艺管理_工艺查询_订单信息查询]
@订单编号 int
AS
SELECT *  FROM[MES_接口_生产计划]  where 订单编号 = @订单编号



GO
/****** Object:  StoredProcedure [dbo].[工艺管理_工艺查询_更新打印次数]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[工艺管理_工艺查询_更新打印次数]
    @订单编号列表 NVARCHAR(MAX)
AS
BEGIN
    SET NOCOUNT ON;
    
    BEGIN TRY
        BEGIN TRANSACTION;
        
        -- 创建临时表存储订单编号
        CREATE TABLE #TempOrders (订单编号 NVARCHAR(100));
        
        -- 解析逗号分隔的订单编号列表
        INSERT INTO #TempOrders (订单编号)
        SELECT value 
        FROM STRING_SPLIT(@订单编号列表, ',')
        WHERE LTRIM(RTRIM(value)) <> '';
        
        -- 更新打印次数
        UPDATE [dbo].[MES_接口_生产计划]
        SET 周转单打印次数 = ISNULL(周转单打印次数, 0) + 1
        WHERE 订单编号 IN (SELECT 订单编号 FROM #TempOrders);
        
        -- 检查更新了多少行
        DECLARE @UpdateCount INT = @@ROWCOUNT;
        
        -- 返回成功信息
        SELECT 
            '成功' AS 状态,
            @UpdateCount AS 更新记录数,
            '成功更新' + CAST(@UpdateCount AS NVARCHAR(10)) + '条记录的打印次数' AS 消息;
        
        DROP TABLE #TempOrders;
        
        COMMIT TRANSACTION;
    END TRY
    BEGIN CATCH
        IF @@TRANCOUNT > 0
            ROLLBACK TRANSACTION;
        
        -- 返回错误信息
        SELECT 
            '错误' AS 状态,
            0 AS 更新记录数,
            ERROR_MESSAGE() AS 消息;
        
        IF OBJECT_ID('tempdb..#TempOrders') IS NOT NULL
            DROP TABLE #TempOrders;
    END CATCH
END


GO
/****** Object:  StoredProcedure [dbo].[工艺管理_工艺查询_生产工艺查询]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[工艺管理_工艺查询_生产工艺查询]
@生产工艺 int,
@PageCurrent 	int=1,             --要显示的页码
@PageSize   	int  = 20,         --每页的大小(记录数)
@PageCount  	int OUTPUT,        --总页数
@ItemCount	    int OUTPUT,	       --数据总数
@物料编号 nvarchar(50),
@生产订单 int,
@状态 int,
@订单状态 int = 1,
@拣配状态 int = 1,

@计划号  NVARCHAR(50)
AS
declare @tbname		sysname --要分页显示的表名
declare @fieldkey	sysname --用于定位记录的主键(惟一键)字段,只能是单个字段
declare @where		nvarchar(4000)	--查询条件
declare @fieldshow	nvarchar(1000) --以逗号分隔的要显示的字段列表,如果不指定,则显示所有字段
declare @fieldOrder	nvarchar(1000) ----以逗号分隔的排序字段列表,可以指定在字段后面指定DESC/ASC  --用于指定排序顺序
declare @GroupBy nvarchar(1000)
--SELECT [StageID] as 工艺编号 ,[StatgeName] as 工艺名称 FROM [基础表_工序] ORDER BY [StageID]

SET @tbname = '[dbo].[View_生产工艺视图]'
SET @fieldkey = '订单编号'
SET @where = '任务状态 is not NULL AND isnull(单据状态,0) <> ''已取消''
AND EXISTS (
                      SELECT 1 FROM [dbo].[MES_接口_生产计划_生产任务] t2 
                      WHERE t2.排产状态 IS NOT NULL 
                      AND t2.订单编号 = [View_生产工艺视图].订单编号
                  )'
SET @fieldshow = '订单编号,零件名称,零件图号,计划数量,周转单打印次数,计划号'
set @fieldOrder = ' 订单编号 ASC '
-- 物料编号条件
IF @物料编号 <> ''
BEGIN
    SET @where = @where + ' AND 生产工艺 = 1 AND 零件图号 = N''' + REPLACE(@物料编号, '''', '''''') + ''''
END



-- 生产订单条件（@生产订单 是 int）
IF @生产订单 IS NOT NULL AND @生产订单 <> 0
BEGIN
    SET @where = @where + ' AND 订单编号 = ' + CAST(@生产订单 AS NVARCHAR(20))
END
IF @计划号 IS NOT NULL AND @计划号 <> 0
BEGIN
    SET @where = @where + ' AND 计划号 = '''+@计划号+''''  
END
-- 状态条件
IF @状态 = 1
    SET @where = @where + ' AND ISNULL(周转单打印次数, 0) > 0'
ELSE IF @状态 = 2
    SET @where = @where + ' AND ISNULL(周转单打印次数, 0) = 0'
IF @订单状态 = 2
    SET @where = @where + ' AND ISNULL(自制件属性, '''') LIKE ''%装配%'''
IF @订单状态 = 1
    SET @where = @where + ' AND ISNULL(自制件属性, 0) = ''机加件'''
IF @拣配状态 = 1
    SET @where = @where + ' AND ISNULL(拣配状态, 0) > 0'
IF @拣配状态 = 2
    SET @where = @where + ' AND ISNULL(拣配状态, 0) = 0'

print @where
SET @GroupBy = ' GROUP BY 订单编号,零件名称,零件图号,计划数量,周转单打印次数,计划号'

exec [dbo].[sp_xt_pagesplit_group] @tbname,@fieldkey,@where,@fieldshow,@fieldOrder,@GroupBy,@PageCurrent,@PageSize,@PageCount out,@ItemCount out
GO
/****** Object:  StoredProcedure [dbo].[工艺管理_工艺任务_订单查询]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[工艺管理_工艺任务_订单查询]
    @订单号 int = 0,
    @合同号 nvarchar(50) = '',
    @产品编码 nvarchar(50) = '',
    @产品名称 nvarchar(50) = '',
    @要求完工日期1 nvarchar(50) = '',
    @要求完工日期2 nvarchar(50) = '',
	@订单状态 int = 1,
    @任务状态 int = 0
AS
BEGIN
    DECLARE @selectStr NVARCHAR(MAX);
    DECLARE @selectStrWhere NVARCHAR(MAX) = ' WHERE p.[生产工艺] = 1 and (单据状态 <> ''已取消'' OR 单据状态 IS NULL) ';
    SET @selectStr = N'
        SELECT 
            p.*
        FROM [MES_接口_生产计划] p ';
    -- 添加筛选条件
    IF @订单号 > 0
        SET @selectStrWhere = @selectStrWhere + ' AND p.[订单编号] = ' + CAST(@订单号 AS VARCHAR(10));
    
    IF @合同号 <> ''
        SET @selectStrWhere = @selectStrWhere + ' AND p.[合同号] LIKE ''%' + @合同号 + '%''';
    
    IF @产品编码 <> ''
        SET @selectStrWhere = @selectStrWhere + ' AND p.[物料编号] LIKE ''%' + @产品编码 + '%''';
    
    IF @产品名称 <> ''
        SET @selectStrWhere = @selectStrWhere + ' AND p.[物料描述] LIKE ''%' + @产品名称 + '%''';
    
    IF @要求完工日期1 <> ''
        SET @selectStrWhere = @selectStrWhere + ' AND p.[计划完成] >= ''' + @要求完工日期1 + '''';
    
    IF @要求完工日期2 <> ''
        SET @selectStrWhere = @selectStrWhere + ' AND p.[计划完成] <= ''' + @要求完工日期2 + '''';
    
    IF @任务状态 = 2
        SET @selectStrWhere = @selectStrWhere + ' AND ISNULL(p.任务状态, 0) = '+ CAST(@任务状态 AS VARCHAR(10));
    IF @任务状态 = 1
        SET @selectStrWhere = @selectStrWhere + ' AND ISNULL(p.任务状态, 0) = 0'
	IF @订单状态 = 2
        SET @selectStrWhere = @selectStrWhere + ' AND ISNULL(p.自制件属性, '''') LIKE ''%装配%'''
    IF @订单状态 = 1
        SET @selectStrWhere = @selectStrWhere + ' AND ISNULL(p.自制件属性, 0) = ''机加件'''
    SET @selectStr = @selectStr + @selectStrWhere;
    PRINT @selectStr;
    EXEC sp_executesql @selectStr;
END
GO
/****** Object:  StoredProcedure [dbo].[工艺管理_工艺维护_查看图纸]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO







CREATE     PROCEDURE [dbo].[工艺管理_工艺维护_查看图纸]

    @物料编号 NVARCHAR(50) = NULL
AS
BEGIN
    SET NOCOUNT ON;
    
    SELECT 
        CASE 
            -- 如果 uploadTime 是有效日期且晚于比较时间，返回 name
            WHEN uploadTime IS NOT NULL 
                 AND ISDATE(uploadTime) = 1 
                 AND CONVERT(DATETIME, uploadTime) >= '2026-01-27 13:01:00'
            THEN name
            -- 其他情况返回 uid
            ELSE uid
        END AS uid
    FROM [dbo].[物料基础数据_工艺图纸]
    WHERE num = @物料编号;
END


GO
/****** Object:  StoredProcedure [dbo].[工艺管理_工艺维护_工艺图查询]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE       PROCEDURE [dbo].[工艺管理_工艺维护_工艺图查询]

@零件图号_check int = null,
@零件图号 nvarchar(50) = null
with recompile
AS
set nocount on;

if @零件图号_check = 1
	SELECT top 50
	  t1.*,
	  t2.物料描述
	FROM  dbo.物料基础数据_工艺图纸 AS t1 LEFT OUTER JOIN
               SAP.SBO_YL.dbo.UBT_OITM AS t2 ON t1.num = t2.物料编码  where num = @零件图号
else
	SELECT top 50
	  t1.*,
	  t2.物料描述
	FROM  dbo.物料基础数据_工艺图纸 AS t1 LEFT OUTER JOIN
               SAP.SBO_YL.dbo.UBT_OITM AS t2 ON t1.num = t2.物料编码
GO
/****** Object:  StoredProcedure [dbo].[工艺管理_工艺维护_删除图纸]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO








CREATE     PROCEDURE [dbo].[工艺管理_工艺维护_删除图纸]

@物料编号  nvarchar(50) = null
AS
set nocount on;

delete [dbo].[物料基础数据_工艺图纸] where num = @物料编号 

GO
/****** Object:  StoredProcedure [dbo].[工艺管理_工艺维护_验证名称]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE       PROCEDURE [dbo].[工艺管理_工艺维护_验证名称]


@零件图号 nvarchar(50) = null
with recompile
AS
set nocount on;

SELECT * FROM [dbo].[物料数据] where 物料编码 = @零件图号
GO
/****** Object:  StoredProcedure [dbo].[工艺管理_获取物料原料信息]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[工艺管理_获取物料原料信息]

@订单编号 nvarchar(50)
AS
SELECT * FROM SAP.SBO_YL.dbo.UBT_OWOR_material  where Docentry = @订单编号




GO
/****** Object:  StoredProcedure [dbo].[工艺管理_零件工序_生产工艺_编辑]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		刘帅
-- Create date: 2021-03-01
-- =============================================
CREATE       PROCEDURE [dbo].[工艺管理_零件工序_生产工艺_编辑]
@idd int,
@工艺要求 nvarchar(500)=null,
@准备工时 int = null,
@标准工时 int = null,
@工时合计 int = null,
@工卡量具 nvarchar(500)=null,
@指定机床 nvarchar(500)=null,
@车间 nvarchar(500)=null,
@备注 nvarchar(500)=null,
@属性 nvarchar(500)=null
 AS
 update 车间生产管理工艺_零件生产工艺_工艺库 set 工艺要求=@工艺要求,准备工时=@准备工时,标准工时 = @标准工时,
 工时合计=@工时合计,工卡量具=@工卡量具,指定机床=@指定机床,车间=@车间,备注 = @备注 ,属性 = @属性 where id = @idd
GO
/****** Object:  StoredProcedure [dbo].[工艺管理_零件工序_生产工艺_编辑插入工序]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:		刘帅
-- Create date: 2021-03-01
-- =============================================
CREATE       PROCEDURE [dbo].[工艺管理_零件工序_生产工艺_编辑插入工序]
@idd int,
@工艺编号 int,
@计划数量 int,
@订单编号 int
 AS
 update 车间生产管理工艺_零件生产工艺_工艺库 set 工艺编号=@工艺编号,计划数量 = @计划数量 where id = @idd
 update 车间生产管理工艺_零件生产工艺_工艺库 set 启用 = 0 where 订单编号 = @订单编号
update [dbo].[MES_接口_生产计划] set 生产工艺 = 0 where 订单编号=@订单编号
GO
/****** Object:  StoredProcedure [dbo].[工艺管理_零件工序_生产工艺_插入工序]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		刘帅
-- Create date: 2021-05-06
-- =============================================
CREATE      PROCEDURE [dbo].[工艺管理_零件工序_生产工艺_插入工序]
@零件图号 nvarchar(50) = null,
@idd int = null,
@订单编号 int = null
AS


declare @工序顺序 int
select @工序顺序 = 工艺顺序 from dbo.车间生产管理工艺_零件生产工艺_工艺库 where  id=@idd 
update dbo.车间生产管理工艺_零件生产工艺_工艺库
set 工艺顺序 = 工艺顺序+1
where 工艺顺序>=@工序顺序 and 零件图号=@零件图号 and 订单编号 = @订单编号
insert dbo.车间生产管理工艺_零件生产工艺_工艺库(零件图号,订单编号,工艺顺序)values(@零件图号,@订单编号, @工序顺序 )
select @工序顺序

update 车间生产管理工艺_零件生产工艺_工艺库 set 启用 = 0 where 订单编号 = @订单编号
update [dbo].[MES_接口_生产计划] set 生产工艺 = 0 where 订单编号=@订单编号
GO
/****** Object:  StoredProcedure [dbo].[工艺管理_零件工序_生产工艺_批量生成生产工艺]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[工艺管理_零件工序_生产工艺_批量生成生产工艺]
    @零件图号 NVARCHAR(MAX),   -- 示例: 'LH-1001,LH-1002'
    @订单编号 NVARCHAR(MAX),   -- 示例: '175,176'
    @计划数量 NVARCHAR(MAX)    -- 示例: '20,160'
AS
BEGIN
    SET NOCOUNT ON;

    -- 参数校验
    IF @零件图号 IS NULL OR @订单编号 IS NULL OR @计划数量 IS NULL
    BEGIN
        RAISERROR('所有参数都必须提供', 16, 1);
        RETURN;
    END;

    DECLARE @sql1 NVARCHAR(MAX);
    DECLARE @sql2 NVARCHAR(MAX);

    -- Step 1: 更新生产计划表
    SET @sql1 = N'
    UPDATE [dbo].[MES_接口_生产计划] 
    SET 生产工艺 = 1 
    WHERE 订单编号 IN (SELECT TRIM(value) FROM STRING_SPLIT(@订单编号, '','')) ;';
	
    EXEC sp_executesql 
        @sql1, 
        N'@订单编号 NVARCHAR(MAX)', 
        @订单编号 = @订单编号;

    -- Step 2: 插入生产工艺数据（三参数一一对应）
    SET @sql2 = N'
    WITH PartList AS (
        SELECT TRIM(value) AS PartID, ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS rn
        FROM STRING_SPLIT(@零件图号, '','')
    ),
    OrderList AS (
        SELECT TRIM(value) AS OrderID, ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS rn
        FROM STRING_SPLIT(@订单编号, '','')
    ),
    QtyList AS (
        SELECT TRIM(value) AS Qty, ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS rn
        FROM STRING_SPLIT(@计划数量, '','')
    ),
    MatchedData AS (
        SELECT 
            p.PartID,
            o.OrderID,
            q.Qty
        FROM PartList p
        INNER JOIN OrderList o ON p.rn = o.rn
        INNER JOIN QtyList q ON p.rn = q.rn
    )
    INSERT INTO 车间生产管理工艺_零件生产工艺_工艺库 
    (
        [零件图号],
        [工艺编号],
        [工艺顺序],
        [工艺要求],
        [是否最后一序],
        [准备工时],
        [标准工时],
        [工时合计],
        [工卡量具],
        [指定机床],
        [车间],
		[备注],
        [计划数量],
        [订单编号],
		[启用]
    )
    SELECT 
        m.PartID,
        src.[工艺编号],
        src.[工艺顺序],
        src.[工艺要求],
        src.[是否最后一序],
        src.[准备工时],
        src.[标准工时],
        src.[工时合计],
        src.[工卡量具],
        src.[指定机床],
        src.[车间],
		src.[备注],
        CAST(m.Qty AS INT),
        m.OrderID,
		1
    FROM MatchedData m
    INNER JOIN 车间生产管理工艺_零件工序_工艺库 src ON m.PartID = src.[零件图号];';
	
    EXEC sp_executesql 
        @sql2, 
        N'@零件图号 NVARCHAR(MAX), @订单编号 NVARCHAR(MAX), @计划数量 NVARCHAR(MAX)',
        @零件图号 = @零件图号,
        @订单编号 = @订单编号,
        @计划数量 = @计划数量;

END;
GO
/****** Object:  StoredProcedure [dbo].[工艺管理_零件工序_生产工艺_删除工序]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		刘帅
-- Create date: 2021-05-06
-- =============================================
CREATE              PROCEDURE [dbo].[工艺管理_零件工序_生产工艺_删除工序] 

@物料编号 nvarchar(50) =null,
@idd int =null,
@订单编号 int
AS



-- 零件工序顺序
declare @工序顺序 int
select @工序顺序=工艺顺序 from 车间生产管理工艺_零件生产工艺_工艺库 where id=@idd

-- 所有零件向上串一行
update 车间生产管理工艺_零件生产工艺_工艺库 set 工艺顺序 = 工艺顺序 - 1
where 工艺顺序>@工序顺序 and 零件图号 = @物料编号 and 订单编号 = @订单编号
-- 删除该零件
delete from 车间生产管理工艺_零件生产工艺_工艺库 where id=@idd
		
update 车间生产管理工艺_零件生产工艺_工艺库 set 启用 = 0 where 订单编号 = @订单编号
update [dbo].[MES_接口_生产计划] set 生产工艺 = 0 where 订单编号=@订单编号
		-- 最大工序顺序
		--declare @工序顺序2 int
		--select  top 1 @工序顺序2 = 工艺顺序 from dbo.车间生产管理工艺_零件工序_工艺库
		--where  零件图号 = @零件图号 order by 工艺顺序 desc
		-- 插入一条
		--set @工序顺序2 = @工序顺序2+1
		--insert dbo.车间生产管理工艺_零件工序_工艺库(零件图号,工艺顺序)
		--values(@零件图号, @工序顺序2)
GO
/****** Object:  StoredProcedure [dbo].[工艺管理_零件工序_生产工艺_上移工序]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:		刘帅
-- Create date: 2021-05-06
-- =============================================
CREATE          PROCEDURE [dbo].[工艺管理_零件工序_生产工艺_上移工序]

@物料编号 nvarchar(50) =null,
@idd int =null,
@订单编号 int
AS


declare @工序顺序 int
declare @前idd int

select @工序顺序 = 工艺顺序 from dbo.车间生产管理工艺_零件生产工艺_工艺库
where  id=@idd

if(@工序顺序=1)
return

select @前idd = id from dbo.车间生产管理工艺_零件生产工艺_工艺库
where  零件图号 = @物料编号 and 工艺顺序=@工序顺序-1 and 订单编号 = @订单编号

update dbo.车间生产管理工艺_零件生产工艺_工艺库
set 工艺顺序 = @工序顺序-1
where id=@idd

update dbo.车间生产管理工艺_零件生产工艺_工艺库
set 工艺顺序 = @工序顺序
where id=@前idd


update 车间生产管理工艺_零件生产工艺_工艺库 set 启用 = 0 where 订单编号 = @订单编号
update [dbo].[MES_接口_生产计划] set 生产工艺 = 0 where 订单编号=@订单编号
GO
/****** Object:  StoredProcedure [dbo].[工艺管理_零件工序_生产工艺_下移工序]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:		刘帅
-- Create date: 2021-03-01
-- =============================================
CREATE          PROCEDURE [dbo].[工艺管理_零件工序_生产工艺_下移工序]
@物料编号 nvarchar(50) =null,
@idd int =null,
@订单编号 int
AS


declare @工序顺序 int
declare @后idd int

select @工序顺序 = 工艺顺序 from dbo.车间生产管理工艺_零件生产工艺_工艺库
where  id=@idd

if(@工序顺序=30)
return

select @后idd = id from dbo.车间生产管理工艺_零件生产工艺_工艺库
where  零件图号 = @物料编号 and 工艺顺序=@工序顺序+1 and 订单编号 = @订单编号

update dbo.车间生产管理工艺_零件生产工艺_工艺库
set 工艺顺序 = @工序顺序+1
where id=@idd

update dbo.车间生产管理工艺_零件生产工艺_工艺库
set 工艺顺序 = @工序顺序
where id=@后idd


update 车间生产管理工艺_零件生产工艺_工艺库 set 启用 = 0 where 订单编号 = @订单编号
update [dbo].[MES_接口_生产计划] set 生产工艺 = 0 where 订单编号=@订单编号
GO
/****** Object:  StoredProcedure [dbo].[工艺管理_零件工序_生产工艺_修改数据]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		刘帅
-- Create date: 2021-05-06
-- =============================================
CREATE   PROCEDURE [dbo].[工艺管理_零件工序_生产工艺_修改数据]

@物料编号 nvarchar(50)=null,
@工艺编号 int =null,
@计划数量 int =null,
@订单编号 int
as

declare @idd int = null
declare @工序顺序 int= 0
select  top 1 @工序顺序 = 工艺顺序  from 车间生产管理工艺_零件生产工艺_工艺库 where 零件图号=@物料编号 and 订单编号 = @订单编号  order by  工艺顺序 desc

insert into dbo.车间生产管理工艺_零件生产工艺_工艺库(计划数量,零件图号,工艺顺序,工艺编号,订单编号)values(@计划数量,@物料编号, @工序顺序+1 ,@工艺编号,@订单编号) 
--update 车间生产管理工艺_零件生产工序_工艺库 set 工艺编号=@工艺编号 where id = @idd

update 车间生产管理工艺_零件生产工艺_工艺库 set 启用 = 0 where 订单编号 = @订单编号
update [dbo].[MES_接口_生产计划] set 生产工艺 = 0 where 订单编号=@订单编号
GO
/****** Object:  StoredProcedure [dbo].[工艺管理_生产工艺_标准工艺拷贝]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[工艺管理_生产工艺_标准工艺拷贝]

AS
SELECT *  FROM (
    SELECT a.零件图号,b.物料描述,a.id,
           ROW_NUMBER() OVER (PARTITION BY a.[零件图号] ORDER BY (SELECT NULL)) AS rn 
	from [dbo].[车间生产管理工艺_零件工序_工艺库] a left join [dbo].[物料数据] b  on a.零件图号=b.物料编码 where a.启用 = 1) t WHERE rn = 1;



GO
/****** Object:  StoredProcedure [dbo].[工艺管理_生产工艺_查询标准工艺]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[工艺管理_生产工艺_查询标准工艺]
@物料编号 nvarchar(50)
AS
SELECT *,dbo.基础表_工序.工序名称 as 工艺名称  FROM [车间生产管理工艺_零件工序_工艺库] left join dbo.基础表_工序
 on [车间生产管理工艺_零件工序_工艺库].工艺编号 = dbo.基础表_工序.工艺编号 where 零件图号 = @物料编号 and 启用 = 1 ORDER BY [工艺顺序] 
GO
/****** Object:  StoredProcedure [dbo].[工艺管理_生产工艺_查询生产工艺]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[工艺管理_生产工艺_查询生产工艺]
@物料编号 nvarchar(50),
@订单编号 int 
AS
SELECT [id]
      ,[零件图号]
      ,a.[工艺编号]
      ,[工艺顺序]
      ,[工艺要求]
      ,[是否最后一序]
      ,[订单编号]
      ,[计划数量]
      ,isnull(准备工时,0) as 准备工时
      ,isnull(标准工时,0) as 标准工时
      ,isnull(工时合计,0) as 工时合计
      ,[工卡量具]
      ,[指定机床]
      ,[车间]
      ,[备注]
      ,[启用]
	  ,属性,b.工序名称 as 工艺名称  FROM [车间生产管理工艺_零件生产工艺_工艺库] as a left join dbo.基础表_工序 as b
 on a.工艺编号  = b.工艺编号 where 零件图号 = @物料编号 and 订单编号 = @订单编号   ORDER BY [工艺顺序] 
GO
/****** Object:  StoredProcedure [dbo].[工艺管理_生产工艺_工艺拷贝]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:		张
-- Create date: 025/9/19 9:46:09
-- =============================================
CREATE      PROCEDURE [dbo].[工艺管理_生产工艺_工艺拷贝]
@物料编号 nvarchar(50)=null,
@零件图号 nvarchar(50)=null,
@订单编号 int,
@计划数量 int,
@工艺类型 int
 AS


declare @工艺数量 int
if(@工艺类型 = 0)
select @工艺数量=count(*) from 车间生产管理工艺_零件工序_工艺库 where 零件图号=@零件图号
if(@工艺类型 = 1)
select @工艺数量=count(*) from 车间生产管理工艺_零件生产工艺_工艺库 where 零件图号=@零件图号

begin
declare  @最大顺序 int 
declare  @新增条数 int 
declare  @l int 
	set @l = 1
	set @新增条数 = @工艺数量
	delete 车间生产管理工艺_零件生产工艺_工艺库 where 订单编号=@订单编号
    while(@l<=@新增条数)
		
			begin
			select @最大顺序=max(工艺顺序) from 车间生产管理工艺_零件生产工艺_工艺库
			
            where 订单编号=@订单编号
			
			insert into 车间生产管理工艺_零件生产工艺_工艺库(订单编号,计划数量,零件图号,工艺顺序,启用)values(@订单编号,@计划数量,@物料编号,ISNULL(@最大顺序,0)+1,0)
			update [dbo].[MES_接口_生产计划] set 生产工艺 = 1 where 订单编号=@订单编号
			set @l=@l+1
			
			end
end

declare  @i int 
	set @i = 1
		while(@i<=@工艺数量)
		
			begin
				declare @工艺编号 int
				declare @工艺要求  nvarchar(500)
				declare @准备工时  int
				declare @标准工时  int
				declare @工时合计  int
				declare @工卡量具  nvarchar(500)
				declare @指定机床  nvarchar(500)
				declare @车间  nvarchar(500)
				declare @备注  nvarchar(500)

				if(@工艺类型 = 0) SELECT @备注 = 备注,@工艺编号= 工艺编号,@工艺要求= 工艺要求,@准备工时= 准备工时,@标准工时= 标准工时,@工时合计= 工时合计,@工卡量具= 工卡量具,@指定机床= 指定机床,@车间= 车间
				FROM dbo.车间生产管理工艺_零件工序_工艺库 
				WHERE 零件图号=@零件图号 and 工艺顺序=@i and 启用 = 1
				if(@工艺类型 = 1) SELECT top 1 @备注 = 备注,@工艺编号= 工艺编号,@工艺要求= 工艺要求,@准备工时= 准备工时,@标准工时= 标准工时,@工时合计= 工时合计,@工卡量具= 工卡量具,@指定机床= 指定机床,@车间= 车间
				FROM dbo.车间生产管理工艺_零件生产工艺_工艺库 
				WHERE 零件图号=@零件图号 and 工艺顺序=@i and 启用 = 1

				update 车间生产管理工艺_零件生产工艺_工艺库 
				set 工艺编号= @工艺编号,
				工艺要求= @工艺要求,
				准备工时= @准备工时,
				标准工时= @标准工时,
				工时合计= @工时合计,
				工卡量具= @工卡量具,
				指定机床= @指定机床,
				车间= @车间,
				备注 = @备注
				where 零件图号=@物料编号 and 工艺顺序=@i and 订单编号 = @订单编号

                set @i=@i+1
			end


GO
/****** Object:  StoredProcedure [dbo].[工艺管理_生产工艺_启用]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:		刘帅
-- Create date: 2021-03-01
-- =============================================
CREATE PROCEDURE [dbo].[工艺管理_生产工艺_启用]
@订单编号 nvarchar(50) = null
 AS
update 车间生产管理工艺_零件生产工艺_工艺库 set 启用 = 1 where 订单编号 = @订单编号
update [dbo].[MES_接口_生产计划] set 生产工艺 = 1 where 订单编号=@订单编号

GO
/****** Object:  StoredProcedure [dbo].[工艺管理_生产工艺_生产工艺拷贝]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[工艺管理_生产工艺_生产工艺拷贝]

AS
SELECT *  FROM (
    SELECT *,
           ROW_NUMBER() OVER (PARTITION BY [物料编号] ORDER BY (SELECT NULL)) AS rn 
	from [MES_接口_生产计划] where 生产工艺 = 1) t WHERE rn = 1;



GO
/****** Object:  StoredProcedure [dbo].[工艺管理_生产计划物料查询]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[工艺管理_生产计划物料查询]
@过滤  NVARCHAR(200)
AS
SELECT top 100 * FROM  [SAP].[SBO_YL].[dbo].[UBT_OITM] where 物料编码 like '' +'%'+@过滤+'%' +''

GO
/****** Object:  StoredProcedure [dbo].[工艺管理_图纸维护_查看图纸]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[工艺管理_图纸维护_查看图纸]
    @物料编号 NVARCHAR(50) = NULL
AS
BEGIN
    SET NOCOUNT ON;
    
    SELECT 
        CASE 
            -- 如果 uploadTime 是有效日期且晚于比较时间，返回 name
            WHEN uploadTime IS NOT NULL 
                 AND ISDATE(uploadTime) = 1 
                 AND CONVERT(DATETIME, uploadTime) >= '2026-01-27 13:01:00'
            THEN name
            -- 其他情况返回 uid
            ELSE uid
        END AS uid
		,worker
    FROM [dbo].[物料基础数据_零件图纸] 
    WHERE num = @物料编号;
END
GO
/****** Object:  StoredProcedure [dbo].[工艺管理_图纸维护_查询删除记录]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[工艺管理_图纸维护_查询删除记录]
	@物料编码 nvarchar(200) = ''
AS
BEGIN
    SET NOCOUNT ON;
    DECLARE @selectStr NVARCHAR(MAX)
    DECLARE @selectStrWhere NVARCHAR(4000) = ' WHERE 1 =1 '
    SET @selectStr = N' SELECT top 50
        物料编号,
        文件名称,
        操作人,
        CONVERT(NVARCHAR(19), 删除时间, 120) AS 删除时间,
        ISNULL(备注, '''') AS 备注
    FROM 物料基础数据_零件图纸删除记录
     ';
	IF (@物料编码 <> '')
        SET @selectStrWhere = @selectStrWhere + ' AND [物料编号] LIKE ''%' + @物料编码 + '%'''
	 -- 添加排序
    SET @selectStrWhere = @selectStrWhere + ' ORDER BY 删除时间 DESC'
    
    -- 合并SQL
    SET @selectStr = @selectStr + @selectStrWhere
    
    -- 打印SQL（调试用）
    PRINT @selectStr
    
    -- 执行查询
    EXEC sp_executesql @selectStr
END;
GO
/****** Object:  StoredProcedure [dbo].[工艺管理_图纸维护_记录删除日志]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[工艺管理_图纸维护_记录删除日志]
    @物料编号 NVARCHAR(100),
    @文件名称 NVARCHAR(255) = NULL,
    @操作人 NVARCHAR(50),
    @备注 NVARCHAR(500) = NULL
AS
BEGIN
    SET NOCOUNT ON;
    
    BEGIN TRY
        INSERT INTO 物料基础数据_零件图纸删除记录 (
            物料编号, 
            文件名称, 
            操作人, 
            删除时间, 
            备注
        )
        VALUES (
            @物料编号,
            @文件名称,
            @操作人,
            GETDATE(),
            @备注
        );
        
        SELECT '1' AS result;
    END TRY
    BEGIN CATCH
        SELECT '0' AS result, ERROR_MESSAGE() AS error_msg;
    END CATCH
END;
GO
/****** Object:  StoredProcedure [dbo].[工艺管理_图纸维护_零件图查询]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE       PROCEDURE [dbo].[工艺管理_图纸维护_零件图查询]


    @零件图号_check int = null,
    @零件图号 nvarchar(50) = null,
    @导入人 nvarchar(50) = null
WITH RECOMPILE
AS
SET NOCOUNT ON;

-- 情况1: 按零件图号筛选
IF @零件图号_check = 1
BEGIN
    -- 如果有导入人参数，按导入人排序
    IF @导入人 IS NOT NULL AND LTRIM(RTRIM(@导入人)) != ''
    BEGIN
        SELECT TOP 50 * 
        FROM [dbo].[View_图纸视图]
        WHERE num LIKE '%' + @零件图号 + '%'
        ORDER BY 
            CASE WHEN worker = @导入人 THEN 0 ELSE 1 END,  -- 指定导入人优先
            uploadTime DESC
    END
    ELSE
    BEGIN
        SELECT TOP 50 * 
        FROM [dbo].[View_图纸视图]
        WHERE num LIKE '%' + @零件图号 + '%'
        ORDER BY uploadTime DESC
    END
END
-- 情况2: 不按零件图号筛选
ELSE
BEGIN
    -- 如果有导入人参数，按导入人排序
    IF @导入人 IS NOT NULL AND LTRIM(RTRIM(@导入人)) != ''
    BEGIN
        SELECT TOP 50 * 
        FROM [dbo].[View_图纸视图]
        ORDER BY 
            CASE WHEN worker = @导入人 THEN 0 ELSE 1 END,  -- 指定导入人优先
            uploadTime DESC
    END
    ELSE
    BEGIN
        SELECT TOP 50 * 
        FROM [dbo].[View_图纸视图]
        ORDER BY uploadTime DESC
    END
END
GO
/****** Object:  StoredProcedure [dbo].[工艺管理_图纸维护_零件图查询采购]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE    PROCEDURE [dbo].[工艺管理_图纸维护_零件图查询采购]

@零件图号_check int = null,
@零件图号 nvarchar(50) = null
with recompile
AS
set nocount on;
if @零件图号_check = 1
	SELECT top 50 * from
	  [dbo].[View_图纸视图]
	WHERE num LIKE '%' + @零件图号 + '%'  and U_BuyToPrint = 'Y'
else
	SELECT top 50 * from
	  [dbo].[View_图纸视图] WHERE  U_BuyToPrint = 'Y'
GO
/****** Object:  StoredProcedure [dbo].[工艺管理_图纸维护_零件图查询全部]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

create       PROCEDURE [dbo].[工艺管理_图纸维护_零件图查询全部]

@零件图号_check int = null,
@零件图号 nvarchar(50) = null
with recompile
AS
set nocount on;
if @零件图号_check = 1
	SELECT top 50 * from
	  [dbo].[View_图纸视图]
	WHERE num LIKE '%' + @零件图号 + '%' 
else
	SELECT top 50 * from
	  [dbo].[View_图纸视图] 
GO
/****** Object:  StoredProcedure [dbo].[工艺管理_图纸维护_删除图纸]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO







CREATE     PROCEDURE [dbo].[工艺管理_图纸维护_删除图纸]
@物料编号 NVARCHAR(100),
    @文件名称 NVARCHAR(255) = NULL,
    @操作人 NVARCHAR(50) = NULL
AS
BEGIN
    SET NOCOUNT ON;
    
    BEGIN TRANSACTION;
    
    BEGIN TRY
        -- 1. 先记录删除日志
        INSERT INTO 物料基础数据_零件图纸删除记录 (
            物料编号, 
            文件名称, 
            操作人, 
            删除时间, 
            备注
        )
        VALUES (
            @物料编号,
            @文件名称,
            ISNULL(@操作人, '系统'),
            GETDATE(),
            '系统删除操作'
        );
        
        -- 2. 执行实际的删除操作（这里需要根据您实际的删除逻辑来修改）
       
		delete [dbo].[物料基础数据_零件图纸] where num = @物料编号 
        
        COMMIT TRANSACTION;
        SELECT '1' AS result;
    END TRY
    BEGIN CATCH
        ROLLBACK TRANSACTION;
        SELECT '0' AS result, ERROR_MESSAGE() AS error_msg;
    END CATCH
END;
GO
/****** Object:  StoredProcedure [dbo].[工艺管理_图纸维护_物料查询]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO





CREATE       PROCEDURE [dbo].[工艺管理_图纸维护_物料查询]
@过滤  NVARCHAR(200)
AS
SELECT top 100 * FROM SAP.SBO_YL.dbo.UBT_OITM where 物料编码 like '' +'%'+@过滤+'%' +''
GO
/****** Object:  StoredProcedure [dbo].[工艺管理_图纸维护_物料查询_采购]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO





CREATE       PROCEDURE [dbo].[工艺管理_图纸维护_物料查询_采购]
@过滤  NVARCHAR(200)
AS
SELECT top 100 * FROM SAP.SBO_YL.dbo.UBT_OITM where 物料编码 like '' +'%'+@过滤+'%' +'' and U_BuyToPrint = 'Y'
GO
/****** Object:  StoredProcedure [dbo].[工艺管理_图纸维护_验证名称]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE       PROCEDURE [dbo].[工艺管理_图纸维护_验证名称]


@零件图号 nvarchar(50) = null
with recompile
AS
set nocount on;

SELECT * FROM [dbo].[物料数据] where 物料编码 = @零件图号
GO
/****** Object:  StoredProcedure [dbo].[工艺管理_制定标准工艺_拷贝工艺保存]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		张
-- Create date: 025/9/19 9:46:09
-- =============================================
CREATE       PROCEDURE [dbo].[工艺管理_制定标准工艺_拷贝工艺保存]
@物料编号 nvarchar(50)=null,
@零件图号 nvarchar(50)=null,
@工艺类型 int
 AS


declare @工艺数量 int
if(@工艺类型 = 0)
select @工艺数量=count(*) from 车间生产管理工艺_零件工序_工艺库 where 零件图号=@零件图号
if(@工艺类型 = 1)
select @工艺数量=count(*) from 车间生产管理工艺_零件生产工艺_工艺库 where 零件图号=@零件图号
begin
declare  @最大顺序 int 
declare  @新增条数 int 
declare  @l int 
	set @l = 1
	set @新增条数 = @工艺数量
	delete 车间生产管理工艺_零件工序_工艺库 where 零件图号=@物料编号
    while(@l<=@新增条数)
		
			begin
			select @最大顺序=max(工艺顺序) from 车间生产管理工艺_零件工序_工艺库
			
            where 零件图号=@物料编号
			
			insert into 车间生产管理工艺_零件工序_工艺库(零件图号,工艺顺序,启用)values(@物料编号,ISNULL(@最大顺序,0)+1,0)
			update [dbo].[MES_接口_生产计划] set 标准工艺 = 1 where 物料编号=@物料编号
			set @l=@l+1
			
	
			end
end

declare  @i int 
	set @i = 1
		while(@i<=@工艺数量)
		
			begin
				declare @工艺编号 int
				declare @工艺要求  nvarchar(500)
				declare @准备工时  int
				declare @标准工时  int
				declare @工时合计  int
				declare @工卡量具  nvarchar(500)
				declare @指定机床  nvarchar(500)
				declare @车间  nvarchar(500)
				declare @备注  nvarchar(500)

				if(@工艺类型 = 0) SELECT @备注 = 备注,@工艺编号= 工艺编号,@工艺要求= 工艺要求,@准备工时= 准备工时,@标准工时= 标准工时,@工时合计= 工时合计,@工卡量具= 工卡量具,@指定机床= 指定机床,@车间= 车间
				FROM dbo.车间生产管理工艺_零件工序_工艺库 
				WHERE 零件图号=@零件图号 and 工艺顺序=@i and 启用 = 1
				if(@工艺类型 = 1) SELECT top 1 @备注 = 备注,@工艺编号= 工艺编号,@工艺要求= 工艺要求,@准备工时= 准备工时,@标准工时= 标准工时,@工时合计= 工时合计,@工卡量具= 工卡量具,@指定机床= 指定机床,@车间= 车间
				FROM dbo.车间生产管理工艺_零件生产工艺_工艺库 
				WHERE 零件图号=@零件图号 and 工艺顺序=@i and 启用 = 1

				update 车间生产管理工艺_零件工序_工艺库 
				set 工艺编号= @工艺编号,
				工艺要求= @工艺要求,
				准备工时= @准备工时,
				标准工时= @标准工时,
				工时合计= @工时合计,
				工卡量具= @工卡量具,
				指定机床= @指定机床,
				车间= @车间,
				备注 = @备注
				where 零件图号=@物料编号 and 工艺顺序=@i

                set @i=@i+1
			end


GO
/****** Object:  StoredProcedure [dbo].[工艺管理_制定标准工艺_拷贝生产工艺]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[工艺管理_制定标准工艺_拷贝生产工艺]
@物料编号 nvarchar(50)
AS
declare  @最大订单 int 
select @最大订单 = max(订单编号) from 车间生产管理工艺_零件生产工艺_工艺库 where 零件图号 = @物料编号 and 启用 = 1
SELECT *,dbo.基础表_工序.工序名称 as 工艺名称  FROM [车间生产管理工艺_零件生产工艺_工艺库] left join dbo.基础表_工序
 on [车间生产管理工艺_零件生产工艺_工艺库].工艺编号 = dbo.基础表_工序.工艺编号 where 零件图号 = @物料编号 and 启用 = 1 and 订单编号 = @最大订单 ORDER BY [工艺顺序] 
GO
/****** Object:  StoredProcedure [dbo].[计划排产_查询计划信息]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE  PROCEDURE [dbo].[计划排产_查询计划信息]
    @订单号 int = 0,
    @物料类型 nvarchar(50) = '',   --自制件、装配件
    @合同号 nvarchar(50) = '',
    @产品编码 nvarchar(50) = '',
    @产品名称 nvarchar(50) = '',
    @工序名称 nvarchar(50) = '',
    @计划开始 nvarchar(50) = '',
    @计划完成 nvarchar(50) = '',
    @排产状态 nvarchar(50) = '全部',  --全部，已完成、未完成
    @指派对象 nvarchar(50) = '全部',
    @计划号 nvarchar(50) = '',
    @发货状态 nvarchar(50) = '全部',  --全部，已发货、未发货
    @齐套 nvarchar(50) = '全部',
    @检验状态 nvarchar(50) = '' , -- 新增：检验状态过滤，空值或''表示全部
	@发料状态 nvarchar(50) = '全部',
	@自制件属性 nvarchar(50) = '全部'
AS
BEGIN
    DECLARE @selectStr NVARCHAR(MAX)
    DECLARE @selectStrWhere NVARCHAR(4000) = ' WHERE [物料类型] = ''pit_Resource'' and [排产状态] = 1 '
    
    SET @selectStr = N'
        SELECT top 300
            v.计划号,
            拣配状态,
			入库数量,
            要求发货日期,
            isnull(发货状态,0) as [发货状态],
            case 
                when isnull(发料状态,0)=1 then ''发料齐套'' 
                when isnull(发料状态,0)=2 then ''发料缺件''
                when isnull(发料状态,0)=0 then ''未发料''
            end as [发料状态],
            case 
                when isnull(齐套,0)=1 then ''是'' 
                when isnull(齐套,0)=0 then ''否''
            end as [齐套],
            自制件属性,
            case 
                when isnull(任务状态,0)=4 then ''已完成'' 
                when isnull(任务状态,0)=2 then ''已开工'' 
                when isnull(任务状态,0)=0 then ''待执行'' 
                when isnull(任务状态,0)=1 then ''可执行''
                else '''' 
            end as [任务状态],
            case 
                when isnull(加工状态,0)=2 then ''辅助开始''
                when isnull(加工状态,0)=3 then ''辅助结束''
                when isnull(加工状态,0)=4 then ''开始加工''
                when isnull(加工状态,0)=5 then ''暂停''
                when isnull(加工状态,0)=6 then ''报工''
                else '''' 
            end as [加工状态],
            [计划数量订单],
            ISNULL(开工时间, 0) AS 开工时间,
            ISNULL(进度, 0) AS 进度,
            v.[TaskAID],
            [合同号],
            v.[订单编号] AS 订单号,
            [订单行号],
            [订单拆分内码] AS 拆分内码,
            [物料编号] AS 产品编码,
            [物料描述] AS 产品名称,
            TRIM(''.'' FROM TRIM(''0'' FROM CAST([计划数量] AS VARCHAR(30)))) AS 计划数量,
            [计划完成] AS 要求完工日期,
            [工序名称],
            完成数量,
            收料数量,
            CASE 
                WHEN [加急状态] = 1 THEN ''加急'' 
                ELSE '''' 
            END AS 加急状态,
            加急数量,
            性质,
            ISNULL(总工时, 0) AS 总工时,
            [占用情况],
            [排产状态],
            [工序计划数量],
            指派对象编号,
            指派对象,
            TRIM(''.'' FROM TRIM(''0'' FROM CAST([指派数量] AS VARCHAR(30)))) AS 指派数量,
            计划开始时间,
            计划完成时间,
            最晚开始时间,
            [派工状态],
            [外协通知],
            [优先级],
            [未完成说明],
            [派工特殊说明],
            [最后编辑人],
            [最后编辑时间],
            [二次派工],
            CASE 
                WHEN zj_终检.计划号 IS NOT NULL THEN ''是'' 
                ELSE ''否'' 
            END AS 终检,
            -- 新增收检相关字段
            ISNULL(zj_收检.合格数合计, 0) AS 收检合格数,
            ISNULL(zj_收检.不合格数合计, 0) AS 收检不合格数,
            ISNULL(zj_收检.合格数合计, 0) + ISNULL(zj_收检.不合格数合计, 0) AS 收检总数,
            生产工艺,
            -- 新增检验状态字段
            CASE 
                WHEN qt.检验数量_8 > 0 AND qt.检验数量_6 > 0 AND qt.检验数量_8 >= qt.检验数量_6 THEN ''已完成''
                WHEN qt.检验数量_8 > 0 AND qt.检验数量_6 > 0 AND qt.检验数量_8 < qt.检验数量_6 THEN ''未完成''
                WHEN qt.检验数量_8 = 0 AND qt.检验数量_6 > 0 THEN ''未完成''
                WHEN qt.检验数量_8 > 0 AND qt.检验数量_6 = 0 THEN ''已完成''  -- 只有类型8的检验也算完成
                ELSE ''未完成''
            END AS 检验状态
        FROM [View_生产订单_MES] v
        -- 终检判断
        LEFT JOIN (
            SELECT DISTINCT 计划号
            FROM dbo.YL_质量检验_质检记录
            WHERE 质检类型 = ''终检''
        ) zj_终检 ON v.[订单编号] = zj_终检.计划号
        -- 收检数量统计
        LEFT JOIN (
            SELECT 
                TaskAID,
                SUM(ISNULL(合格数, 0)) AS 合格数合计,
                SUM(ISNULL(不合格数, 0)) AS 不合格数合计
            FROM dbo.YL_质量检验_质检记录
            WHERE 质检类型 = ''收检''
            GROUP BY TaskAID
        ) zj_收检 ON v.[TaskAID] = zj_收检.TaskAID
        -- 新增：检验数据统计
        LEFT JOIN (
            SELECT 
                TaskAID,
                SUM(CASE WHEN 检测类型编号 = 6 THEN 检验数量 ELSE 0 END) AS 检验数量_6,
                SUM(CASE WHEN 检测类型编号 = 8 THEN 检验数量 ELSE 0 END) AS 检验数量_8
            FROM YL_质量检验_质检记录
            GROUP BY TaskAID
        ) qt ON v.[TaskAID] = qt.TaskAID  '
    
    -- 添加筛选条件
    IF (@订单号 > 0)
        SET @selectStrWhere = @selectStrWhere + ' AND [订单编号] = ' + CONVERT(VARCHAR(10), @订单号)
    IF (@计划号 > 0)
        SET @selectStrWhere = @selectStrWhere + ' AND v.[计划号] = '''+@计划号+''''
    IF (@合同号 <> '')
        SET @selectStrWhere = @selectStrWhere + ' AND [合同号] LIKE ''%' + @合同号 + '%'''
    
    IF (@产品编码 <> '')
        SET @selectStrWhere = @selectStrWhere + ' AND [物料编号] LIKE ''%' + @产品编码 + '%'''
    
    IF (@产品名称 <> '')
        SET @selectStrWhere = @selectStrWhere + ' AND [物料描述] LIKE ''%' + @产品名称 + '%'''
    
    IF (@工序名称 <> '')
        SET @selectStrWhere = @selectStrWhere + ' AND [工序名称] = ''' + @工序名称 + ''''
    
    IF (@计划开始 <> '')
        SET @selectStrWhere = @selectStrWhere + ' AND [计划开始时间] >= ''' + @计划开始 + ''''
    
    IF (@计划完成 <> '')
        SET @selectStrWhere = @selectStrWhere + ' AND [计划开始时间] <= ''' + @计划完成 + ''''
    
	
    IF (@发货状态 = '未发货')
        SET @selectStrWhere = @selectStrWhere + ' AND ISNULL([发货状态], 0) = 0'
    ELSE IF (@发货状态 = '已发货')
        SET @selectStrWhere = @selectStrWhere + ' AND [发货状态] = 1'
	IF (@自制件属性 = '机加')
        SET @selectStrWhere = @selectStrWhere + ' AND ISNULL([自制件属性], 0) = ''机加件'''
    ELSE IF (@自制件属性 = '装配')
        SET @selectStrWhere = @selectStrWhere + ' AND [自制件属性] like ''%装配%'''
	IF (@发料状态 = '发料齐套')
        SET @selectStrWhere = @selectStrWhere + ' AND ISNULL([发料状态], 0) = 1'
    ELSE IF (@发料状态 = '发料缺件')
        SET @selectStrWhere = @selectStrWhere + ' AND ISNULL([发料状态], 0) = 2'
	ELSE IF (@发料状态 = '发料缺件')
        SET @selectStrWhere = @selectStrWhere + ' AND ISNULL([发料状态], 0) = 0'

    IF (@齐套 = '否')
        SET @selectStrWhere = @selectStrWhere + ' AND ISNULL([齐套], 0) = 0'
    ELSE IF (@齐套 = '是')
        SET @selectStrWhere = @selectStrWhere + ' AND [齐套] = 1'

    IF (@指派对象 <> '全部')
        SET @selectStrWhere = @selectStrWhere + ' AND [指派对象] IN (SELECT value FROM STRING_SPLIT(''' + @指派对象 + ''', '',''))'
    
    -- 新增：检验状态过滤
    IF (@检验状态 <> '')
    BEGIN
        IF (@检验状态 = '已完成')
        BEGIN
            SET @selectStrWhere = @selectStrWhere + ' AND (
                CASE 
                    WHEN qt.检验数量_8 > 0 AND qt.检验数量_6 > 0 AND qt.检验数量_8 >= qt.检验数量_6 THEN ''已完成''

                    ELSE ''未完成''
                END = ''已完成''
            )'
        END
        ELSE IF (@检验状态 = '未完成')
        BEGIN
            SET @selectStrWhere = @selectStrWhere + ' AND (
                CASE 
                    WHEN qt.检验数量_8 > 0 AND qt.检验数量_6 > 0 AND qt.检验数量_8 >= qt.检验数量_6 THEN ''已完成''

                    ELSE ''未完成''
                END = ''未完成''
            )'
        END
    END
    
    -- 添加排序
    SET @selectStrWhere = @selectStrWhere + ' ORDER BY  计划开始时间 asc'
    
    -- 合并SQL
    SET @selectStr = @selectStr + @selectStrWhere
    
    -- 打印SQL（调试用）
    PRINT @selectStr
    
    -- 执行查询
    EXEC sp_executesql @selectStr
END
GO
/****** Object:  StoredProcedure [dbo].[计划排产_二次派工]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:		<Author,,李显>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
create PROCEDURE [dbo].[计划排产_二次派工]
@TaskAID  int,
@personnel nvarchar(500)
AS
BEGIN
update [dbo].[MES_接口_生产计划_生产任务] set 二次派工 = @personnel where AID = @TaskAID
END
GO
/****** Object:  StoredProcedure [dbo].[计划排产_更新齐套数据]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

 

create PROCEDURE [dbo].[计划排产_更新齐套数据]
	@AID int = 0,
	@count real = 0.0
	
AS 


 UPDATE MES_接口_生产计划 SET [齐套] = @count 
 WHERE [订单编号] = @AID
GO
/****** Object:  StoredProcedure [dbo].[计划排产_派工]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		赵艳华
-- Create date: 2025-03-30
-- Description:	计划排产、拆分
-- =============================================
CREATE PROCEDURE [dbo].[计划排产_派工] 
@订单编号列表 NVARCHAR(MAX),
@派工操作人  NVARCHAR(50)
AS
begin
SET NOCOUNT ON;
    

        BEGIN TRANSACTION;
        
        -- 创建临时表存储订单编号
        CREATE TABLE #TempOrders (订单编号 NVARCHAR(100));
        
        -- 解析逗号分隔的订单编号列表
        INSERT INTO #TempOrders (订单编号)
        SELECT value 
        FROM STRING_SPLIT(@订单编号列表, ',')
        WHERE LTRIM(RTRIM(value)) <> '';
        
        -- 更新打印次数
        UPDATE [dbo].[MES_接口_生产计划_生产任务]
	   SET 
		  [派工状态] = 1
		  ,[派工时间] = getdate()
		  ,[修改时间] = getdate()
		  ,[派工操作人] = @派工操作人
		WHERE AID IN (SELECT 订单编号 FROM #TempOrders);
        
        -- 检查更新了多少行
        DECLARE @UpdateCount INT = @@ROWCOUNT;
        
        -- 返回成功信息
        SELECT 
            '成功' AS 状态,
            @UpdateCount AS 更新记录数,
            '成功更新' + CAST(@UpdateCount AS NVARCHAR(10)) + '条记录的信息' AS 消息;
        
        DROP TABLE #TempOrders;
        
        COMMIT TRANSACTION;
    
	
end
GO
/****** Object:  StoredProcedure [dbo].[计划排产_生产订单_订单查询]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[计划排产_生产订单_订单查询]
    @订单号 int = 0,
    @合同号 nvarchar(50) = '',
    @产品编码 nvarchar(50) = '',
    @产品名称 nvarchar(50) = '',
    @下达日期1 nvarchar(50) = '',
    @下达日期2 nvarchar(50) = '',
    @任务状态 int = 1,
	@订单状态 int = 1,
    @工艺状态 int,
	@计划号 nvarchar(50) = '',
	@PageCurrent 	int=1,             --要显示的页码
	@PageSize   	int  = 20,         --每页的大小(记录数)
	@PageCount  	int OUTPUT,        --总页数
	@ItemCount	    int OUTPUT	       --数据总数

AS
BEGIN
	declare @tbname		sysname --要分页显示的表名
	declare @fieldkey	sysname --用于定位记录的主键(惟一键)字段,只能是单个字段
	declare @where		nvarchar(4000)	--查询条件
	declare @fieldshow	nvarchar(1000) --以逗号分隔的要显示的字段列表,如果不指定,则显示所有字段
	declare @fieldOrder	nvarchar(1000) ----以逗号分隔的排序字段列表,可以指定在字段后面指定DESC/ASC  --用于指定排序顺序
	declare @GroupBy nvarchar(1000)
    --DECLARE @selectStr NVARCHAR(MAX);
    --DECLARE @where NVARCHAR(MAX) = ' WHERE (单据状态 <> ''已取消'' OR 单据状态 IS NULL) ';
	set @tbname = '[dbo].[View_生产计划零件图纸视图]'
	set @fieldkey = ' 订单编号 '
	set @where = ' (单据状态 <> ''已取消'' OR 单据状态 IS NULL) '
	set @fieldshow =''
	set @fieldOrder = '订单编号 DESC'
    --SET @selectStr = N'
    --    SELECT 
    --        *
    --    FROM [MES_接口_生产计划] p ';
    -- 添加筛选条件
    IF @订单号 > 0
        SET @where = @where + ' AND [订单编号] = ' + CAST(@订单号 AS VARCHAR(10));
    IF @计划号 IS NOT NULL AND @计划号 <> 0
		BEGIN
			SET @where = @where + ' AND 计划号 = '''+@计划号+''''  
		END
    IF @合同号 <> ''
        SET @where = @where + ' AND [合同号] LIKE ''%' + @合同号 + '%''';
    
    IF @产品编码 <> ''
        SET @where = @where + ' AND [物料编号] LIKE ''%' + @产品编码 + '%''';
    
    IF @产品名称 <> ''
        SET @where = @where + ' AND [物料描述] LIKE ''%' + @产品名称 + '%''';
    
    IF @下达日期1<> ''
        SET @where = @where + ' AND 下达日期 >= ''' + @下达日期1 + '''';
    
    IF @下达日期2 <> ''
        SET @where = @where + ' AND 下达日期 <= ''' + @下达日期2 + '''';
    
    IF @任务状态 = 2
        SET @where = @where + ' AND ISNULL(任务状态, 0) = '+ CAST(@任务状态 AS VARCHAR(10));
    IF @任务状态 = 1
        SET @where = @where + ' AND ISNULL(任务状态, 0) = 0'
	IF @订单状态 = 2
        SET @where = @where + ' AND ISNULL(自制件属性, '''') LIKE ''%装配%'''
    IF @订单状态 = 1
        SET @where = @where + ' AND ISNULL(自制件属性, 0) = ''机加件'''
	IF @工艺状态 = 1
        SET @where = @where + ' AND ISNULL(标准工艺,0) = 1'
    IF @工艺状态 = 2
        SET @where = @where + ' AND ISNULL(生产工艺,0) = 1'
    
    --SET @selectStr = @selectStr + @where;
    PRINT @where;
    --EXEC sp_executesql @selectStr;
	exec [dbo].[sp_xt_pagesplit] @tbname,@fieldkey,@where,@fieldshow,@fieldOrder,@PageCurrent,@PageSize,@PageCount out,@ItemCount out
END
GO
/****** Object:  StoredProcedure [dbo].[计划排产_生产订单_订单任务]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[计划排产_生产订单_订单任务]
    @订单编号 nvarchar(max)
AS
BEGIN
    SET NOCOUNT ON;
    
    PRINT @订单编号;
    
    DECLARE @selectStr1 NVARCHAR(MAX);
    DECLARE @selectStr2 NVARCHAR(MAX);
    DECLARE @自制件属性 NVARCHAR(50);
    
    -- 修复：使用字符串分割函数来匹配多个订单编号
    SELECT TOP 1 @自制件属性 = ISNULL(自制件属性, '0') 
    FROM [dbo].[MES_接口_生产计划] 
    WHERE 订单编号 IN (SELECT TRIM(value) FROM STRING_SPLIT(@订单编号, ','));
    
    IF (@自制件属性 = '机加件')
    BEGIN
        SET @selectStr2 = N'
        INSERT INTO [dbo].[MES_接口_生产计划_生产任务] (
            不装配, 订单编号, 计划数量, 物料编码, 订单行号, 顺序编号,
            工序名称, 物料名称, 订单发货类型, 物料类型, 基本数量, 
            已发货数量, 订单拆分内码, 阶段标识, 可视订单
        )
        SELECT 
            '''', -- 不装配
            src.订单编号,
            src.计划数量,
            src.零件图号 AS 物料编码,
            src.工艺顺序 AS 订单行号,
            src.工艺编号 AS 顺序编号,
            ISNULL(gx.工序名称, '''') AS 工序名称,
            ISNULL(ms.物料描述, '''') AS 物料名称,
            ''im_Manual'', -- 订单发货类型
            ''pit_Resource'', -- 物料类型
            0, -- 基本数量
            0, -- 已发货数量
            1, -- 订单拆分内码
            -1, -- 阶段标识
            1  -- 可视订单
        FROM (
            SELECT 
                订单编号, 零件图号, 工艺顺序, 工艺编号, 计划数量,
                ROW_NUMBER() OVER (
                    PARTITION BY 订单编号, 零件图号, 工艺顺序
                    ORDER BY (SELECT NULL)
                ) AS rn
            FROM 车间生产管理工艺_零件生产工艺_工艺库
            WHERE 订单编号 IN (SELECT TRIM(value) FROM STRING_SPLIT(@订单编号, '',''))
        ) AS src
        LEFT JOIN dbo.基础表_工序 gx ON src.工艺编号 = gx.工艺编号
        LEFT JOIN [dbo].[MES_接口_生产计划] ms ON src.订单编号 = ms.订单编号
        WHERE src.rn = 1;';
        
        SET @selectStr1 = N'
        UPDATE [dbo].[MES_接口_生产计划] 
        SET 任务状态 = 2
        WHERE 订单编号 IN (SELECT TRIM(value) FROM STRING_SPLIT(@订单编号, '',''));';
        
        EXEC sp_executesql 
            @selectStr1, 
            N'@订单编号 NVARCHAR(MAX)', 
            @订单编号 = @订单编号;
    END
    
    IF (@自制件属性 LIKE '%装配%')
    BEGIN
        SET @selectStr2 = N'
        INSERT INTO [dbo].[MES_接口_生产计划_生产任务] (
            不装配, 订单编号, 计划数量, 物料编码, 订单行号, 顺序编号,
            工序名称, 物料名称, 订单发货类型, 物料类型, 基本数量, 
            已发货数量, 订单拆分内码, 阶段标识, 可视订单, 计划开始时间, 计划完成时间, 指派对象
        )
        SELECT 
            '''', -- 不装配
            src.订单编号,
            src.计划数量,
            src.零件图号 AS 物料编码,
            src.工艺顺序 AS 订单行号,
            src.工艺编号 AS 顺序编号,
            ISNULL(gx.工序名称, '''') AS 工序名称,
            ISNULL(ms.物料描述, '''') AS 物料名称,
            ''im_Manual'', -- 订单发货类型
            ''pit_Resource'', -- 物料类型
            0, -- 基本数量
            0, -- 已发货数量
            1, -- 订单拆分内码
            -1, -- 阶段标识
            1,  -- 可视订单
            ms.预计齐套时间,
            ms.计划完成,
            ms.自制件属性
        FROM (
            SELECT 
                订单编号, 零件图号, 工艺顺序, 工艺编号, 计划数量,
                ROW_NUMBER() OVER (
                    PARTITION BY 订单编号, 零件图号, 工艺顺序
                    ORDER BY (SELECT NULL)
                ) AS rn
            FROM 车间生产管理工艺_零件生产工艺_工艺库
            WHERE 订单编号 IN (SELECT TRIM(value) FROM STRING_SPLIT(@订单编号, '',''))
        ) AS src
        LEFT JOIN dbo.基础表_工序 gx ON src.工艺编号 = gx.工艺编号
        LEFT JOIN [dbo].[MES_接口_生产计划] ms ON src.订单编号 = ms.订单编号
        WHERE src.rn = 1;';
        
        SET @selectStr1 = N'
        UPDATE [dbo].[MES_接口_生产计划] 
        SET 任务状态 = 2
        WHERE 订单编号 IN (SELECT TRIM(value) FROM STRING_SPLIT(@订单编号, '',''));';
        
        EXEC sp_executesql 
            @selectStr1, 
            N'@订单编号 NVARCHAR(MAX)', 
            @订单编号 = @订单编号;
    END
    
    PRINT @selectStr2;
    
    EXEC sp_executesql 
        @selectStr2, 
        N'@订单编号 NVARCHAR(MAX)', 
        @订单编号 = @订单编号;
END
GO
/****** Object:  StoredProcedure [dbo].[计划排产_生产订单_订单任务_单条生产工艺任务下发]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[计划排产_生产订单_订单任务_单条生产工艺任务下发]
    @订单编号 NVARCHAR(50),
    @物料编号 NVARCHAR(50),
    @计划数量 INT,
    @工艺顺序 INT
AS
BEGIN
    SET NOCOUNT ON;

    -- 安全处理输入参数（防止SQL注入）
    DECLARE @Safe物料编号 NVARCHAR(50) = REPLACE(@物料编号, '''', '''''')
    DECLARE @Safe订单编号 NVARCHAR(50) = REPLACE(@订单编号, '''', '''''')
    DECLARE @Safe工艺顺序 NVARCHAR(10) = CAST(@工艺顺序 AS NVARCHAR(10))

    BEGIN TRY
        BEGIN TRANSACTION;
		
        -- 步骤1：将后续工序的 订单行号 +1
        UPDATE dbo.MES_接口_生产计划_生产任务
        SET 订单行号 = 订单行号 + 1
        WHERE 订单编号 = @订单编号
          AND 物料编码 = @物料编号
          AND 订单行号 >= @工艺顺序;

        -- 步骤2：构建动态SQL插入新工序
        DECLARE @SQL NVARCHAR(MAX)
        SET @SQL = '
        INSERT INTO [dbo].[MES_接口_生产计划_生产任务] 
        (
            不装配,
            订单编号,
            计划数量,
            物料编码,
            订单行号,
            顺序编号,
            工序名称,
            物料名称,
            订单发货类型,
            物料类型,
            基本数量,
            已发货数量,
            订单拆分内码,
            阶段标识,
            可视订单
        )
        SELECT 
            ''4'' AS 不装配,
            g.订单编号,
            g.计划数量,
            g.零件图号 AS 物料编码,
            g.工艺顺序 AS 订单行号,
            g.工艺编号 AS 顺序编号,
            xg.工序名称,
            mp.物料描述 AS 物料名称,
            ''im_Manual'' AS 订单发货类型,
            ''pit_Resource'' AS 物料类型,
            0 AS 基本数量,
            0 AS 已发货数量,
            1 AS 订单拆分内码,
            -1 AS 阶段标识,
            1 AS 可视订单
        FROM 车间生产管理工艺_零件生产工艺_工艺库 g
        LEFT JOIN dbo.基础表_工序 xg ON g.工艺编号 = xg.工艺编号
        LEFT JOIN dbo.MES_接口_生产计划 mp ON g.零件图号 = mp.物料编号 AND mp.订单编号 = g.订单编号
        WHERE g.零件图号 = ''' + @Safe物料编号 + '''
          AND mp.订单编号 = ''' + @Safe订单编号 + '''
          AND g.工艺顺序 = ' + @Safe工艺顺序 + ';'

        -- 打印SQL用于调试
        PRINT @SQL

        -- 执行插入
        EXEC sp_executesql @SQL
		update [dbo].[MES_接口_生产计划] set 任务状态 = 2 where 订单编号 = @订单编号
		update [dbo].[MES_接口_生产计划] set 生产工艺 = 1 where 订单编号 = @订单编号
		update 车间生产管理工艺_零件生产工艺_工艺库 set 启用 = 1 where 订单编号 = @订单编号
        COMMIT TRANSACTION;
    END TRY
    BEGIN CATCH
        IF @@TRANCOUNT > 0
            ROLLBACK TRANSACTION;

        -- 抛出错误
        THROW;
    END CATCH
END
GO
/****** Object:  StoredProcedure [dbo].[计划排产_生产订单_订单任务_生产工艺任务下发]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[计划排产_生产订单_订单任务_生产工艺任务下发]
@订单编号 nvarchar(max),
@物料编号 nvarchar(max),
@计划数量 int
AS

declare @selectStr2 nvarchar(max)
declare @任务状态 int
declare @自制件属性 nvarchar(50)
select @任务状态 =  isnull(任务状态,0) from [dbo].[MES_接口_生产计划] where 订单编号 = @订单编号
select @自制件属性 =  isnull(自制件属性,0) from [dbo].[MES_接口_生产计划] where 订单编号 = @订单编号
if (@任务状态 <> 2 and @自制件属性 = '机加件')
begin
	
	set @selectStr2=
	'insert into [dbo].[MES_接口_生产计划_生产任务] (不装配,订单编号,计划数量,物料编码,订单行号,顺序编号,工序名称,物料名称,订单发货类型,物料类型,基本数量,已发货数量,订单拆分内码,阶段标识,可视订单) 
	select 
	不装配 = ''1'',
	车间生产管理工艺_零件生产工艺_工艺库.订单编号,
	车间生产管理工艺_零件生产工艺_工艺库.计划数量,
	车间生产管理工艺_零件生产工艺_工艺库.零件图号 as 物料编码,
	车间生产管理工艺_零件生产工艺_工艺库.工艺顺序 as 订单行号,
	车间生产管理工艺_零件生产工艺_工艺库.工艺编号 as 顺序编号,
	dbo.基础表_工序.工序名称 as 工序名称,
	dbo.MES_接口_生产计划.物料描述 as 物料名称,
	订单发货类型 = ''im_Manual'',
	物料类型 = ''pit_Resource'',
	基本数量 = 0,
	已发货数量 = 0,
	订单拆分内码 = 1,
	阶段标识 = -1,
	可视订单 = 1
	from 车间生产管理工艺_零件生产工艺_工艺库 left join dbo.基础表_工序
	on 车间生产管理工艺_零件生产工艺_工艺库.工艺编号 = dbo.基础表_工序.工艺编号
	left join [dbo].[MES_接口_生产计划] on 车间生产管理工艺_零件生产工艺_工艺库.订单编号 = MES_接口_生产计划.订单编号
	where 车间生产管理工艺_零件生产工艺_工艺库.零件图号 ='''+@物料编号+'''and MES_接口_生产计划.订单编号 = '''+@订单编号+''''
	EXEC sp_executesql @selectStr2
	update [dbo].[MES_接口_生产计划] set 任务状态 = 2 where 订单编号 = @订单编号
	update [dbo].[MES_接口_生产计划] set 生产工艺 = 1 where 订单编号 = @订单编号
	update 车间生产管理工艺_零件生产工艺_工艺库 set 启用 = 1 where 订单编号 = @订单编号
end

if (@任务状态 <> 2 and @自制件属性 like '%装配%')
begin
	
	set @selectStr2=
	'insert into [dbo].[MES_接口_生产计划_生产任务] (不装配,订单编号,计划数量,物料编码,订单行号,
	顺序编号,工序名称,物料名称,订单发货类型,物料类型,基本数量,已发货数量,订单拆分内码,阶段标识,可视订单
	,计划开始时间,计划完成时间,指派对象) 
	select 
	不装配 = ''2'',
	车间生产管理工艺_零件生产工艺_工艺库.订单编号,
	车间生产管理工艺_零件生产工艺_工艺库.计划数量,
	车间生产管理工艺_零件生产工艺_工艺库.零件图号 as 物料编码,
	车间生产管理工艺_零件生产工艺_工艺库.工艺顺序 as 订单行号,
	车间生产管理工艺_零件生产工艺_工艺库.工艺编号 as 顺序编号,
	dbo.基础表_工序.工序名称 as 工序名称,
	dbo.MES_接口_生产计划.物料描述 as 物料名称,
	订单发货类型 = ''im_Manual'',
	物料类型 = ''pit_Resource'',
	基本数量 = 0,
	已发货数量 = 0,
	订单拆分内码 = 1,
	阶段标识 = -1,
	可视订单 = 1,
	dbo.MES_接口_生产计划.预计齐套时间 ,
	dbo.MES_接口_生产计划.计划完成 ,
	dbo.MES_接口_生产计划.自制件属性 
	from 车间生产管理工艺_零件生产工艺_工艺库 left join dbo.基础表_工序
	on 车间生产管理工艺_零件生产工艺_工艺库.工艺编号 = dbo.基础表_工序.工艺编号
	left join [dbo].[MES_接口_生产计划] on 车间生产管理工艺_零件生产工艺_工艺库.订单编号 = MES_接口_生产计划.订单编号
	where 车间生产管理工艺_零件生产工艺_工艺库.零件图号 ='''+@物料编号+'''and MES_接口_生产计划.订单编号 = '''+@订单编号+''''
	print @selectStr2
	EXEC sp_executesql @selectStr2
	update [dbo].[MES_接口_生产计划] set 任务状态 = 2 where 订单编号 = @订单编号
	update [dbo].[MES_接口_生产计划] set 生产工艺 = 1 where 订单编号 = @订单编号
	update 车间生产管理工艺_零件生产工艺_工艺库 set 启用 = 1 where 订单编号 = @订单编号
end
if (@任务状态 = 2)
begin
select 0 as result
end

GO
/****** Object:  StoredProcedure [dbo].[计划排产_生产订单_工艺查询]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		刘帅
-- Create date: 2021-03-01
-- =============================================
CREATE PROCEDURE [dbo].[计划排产_生产订单_工艺查询]

 AS

SELECT dbo.车间生产管理工艺_零件工序_工艺库.id, 
      dbo.车间生产管理工艺_零件工序_工艺库.工艺要求, 
      dbo.车间生产管理工艺_零件工序_工艺库.工艺编号, 
      dbo.基础表_工序.工序名称 as 工艺名称 ,
      dbo.车间生产管理工艺_零件工序_工艺库.工艺顺序, 
      零件图号
FROM 车间生产管理工艺_零件工序_工艺库 left join dbo.基础表_工序
 on 车间生产管理工艺_零件工序_工艺库.工艺编号 = dbo.基础表_工序.工艺编号
order by dbo.车间生产管理工艺_零件工序_工艺库.工艺顺序
GO
/****** Object:  StoredProcedure [dbo].[计划排产_生产订单_已排产订单查询]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[计划排产_生产订单_已排产订单查询]

AS
BEGIN
   select * from [dbo].[MES_接口_生产计划_生产任务] where 排产状态 =1
END
GO
/****** Object:  StoredProcedure [dbo].[计划排产_生产订单关闭_查询订单]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[计划排产_生产订单关闭_查询订单]
@订单号 nvarchar(100) = '',
@单据状态 nvarchar(100) = ''
as
begin
    declare @selectStr nvarchar(4000)
    declare @selectStrWhere nvarchar(4000) = ' WHERE (v.加工工时 > 0 OR v.总时长 > 0) 
      AND v.Expr1 IS NOT NULL  
     '
    
    set @selectStr = '
    SELECT 
       v.订单号,
       MAX(产品名称) as 产品名称,
       MAX(产品编码) as 产品编码,
       MAX(入库数量) as 入库数量,
       MAX(合同号) as 合同号,
       MAX(终检不合格数合计) as 终检不合格数合计,
       MAX(终检合格数合计) as 终检合格数合计,
       MAX(合格数合计) as 合格数合计,
       MAX(不合格数合计) as 不合格数合计,
       MAX(计划数量) as 计划数量,
       min(完成数量)  as 完成数量,
       MAX(确认状态) as 确认状态,
       MAX(单据状态) as 单据状态
    FROM [dbo].[View_生产工时视图] AS v
    LEFT JOIN (
        SELECT 
            TaskAID,
            SUM(ISNULL(合格数, 0)) AS 合格数合计,
            SUM(ISNULL(不合格数, 0)) AS 不合格数合计
        FROM dbo.YL_质量检验_质检记录
        WHERE 质检类型 = ''收检''
        GROUP BY TaskAID
    ) zj_收检 ON v.[TaskAID] = zj_收检.TaskAID 
    LEFT JOIN (
        SELECT 
            TaskAID,
            SUM(ISNULL(合格数, 0)) AS 终检合格数合计,
            SUM(ISNULL(不合格数, 0)) AS 终检不合格数合计
        FROM dbo.YL_质量检验_质检记录
        WHERE 质检类型 = ''终检''
        GROUP BY TaskAID
    ) zj_终检数量 ON v.[TaskAID] = zj_终检数量.TaskAID'
    
    if(@订单号 != '') 
        set @selectStrWhere = @selectStrWhere + ' and v.[订单号] = ''' + @订单号 + ''' '
    if(@单据状态='已关闭') 
        set @selectStrWhere = @selectStrWhere + ' and [单据状态] = ''已关闭'''
    else if(@单据状态='未关闭') 
        set @selectStrWhere = @selectStrWhere + ' and [单据状态] is null'
        
    set @selectStrWhere = @selectStrWhere + ' group by v.订单号'
    set @selectStr = @selectStr + @selectStrWhere
    
    -- 执行原查询
    print @selectStr
    EXEC sp_executesql @selectStr
    
    -- 判断传入的订单号是否在查询结果中
    if @订单号 != ''
    begin
        declare @orderInResult int = 0
        
        -- 使用临时表存储查询结果，判断订单是否存在
        create table #tempResult (订单号 nvarchar(100))
        
        insert into #tempResult (订单号)
        EXEC sp_executesql @selectStr
        
        if exists(select 1 from #tempResult where 订单号 = @订单号)
        begin
            select @订单号 as 订单号, '有工时未校验，关闭失败' as 提示信息
        end
        else
        begin
            update [dbo].[MES_接口_生产计划] 
            set 单据状态 = '已关闭' 
            where 订单编号 = @订单号
            
            if @@ROWCOUNT > 0
                select @订单号 as 订单号, '关闭成功' as 提示信息
            else
                select @订单号 as 订单号, '未找到对应订单，关闭失败' as 提示信息
        end
        
        drop table #tempResult
    end
end
GO
/****** Object:  StoredProcedure [dbo].[计划排产_生产订单关闭_查询全部订单]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[计划排产_生产订单关闭_查询全部订单]
@订单号 nvarchar(100) = '',
@单据状态 nvarchar(100) = '',  -- 可选值：'已关闭'、'未关闭'、'可关闭'
@属性 nvarchar(100) = ''
as
declare @selectStr nvarchar(4000)
declare @selectStrWhere nvarchar(4000)=' WHERE 1=1 '

-- 判断是否为可关闭查询
if(@单据状态 = '可关闭')
begin
    set @selectStr = '
	SELECT top 100
     v.订单号 as 订单编号,
	MAX(产品名称) as 产品名称,
    MAX(产品编码) as 产品编码,
    MAX(入库数量) as 入库数量,
    MAX(合同号) as 合同号,
    MAX(终检不合格数合计) as 终检不合格数合计,
    MAX(终检合格数合计) as 终检合格数合计,
    MAX(计划数量) as 计划数量,
    MAX(确认状态) as 确认状态,
    MAX(单据状态) as 单据状态,
	MAX(不合格数合计) as 不合格数合计,
	MIN(CASE WHEN v.Expr1 IS NULL THEN 0 ELSE 1 END) as 是否全部校验
	FROM     dbo.View_生产工时视图 AS v LEFT OUTER JOIN
					   (SELECT  计划号, SUM(ISNULL(合格数, 0)) AS 合格数合计, SUM(ISNULL(不合格数, 0)) AS 不合格数合计
					   FROM     dbo.YL_质量检验_质检记录
					   WHERE   (质检类型 = ''收检'')
					   GROUP BY 计划号) AS zj_收检 ON v.订单号 = zj_收检.计划号 LEFT OUTER JOIN
					   (SELECT  计划号, SUM(ISNULL(合格数, 0)) AS 终检合格数合计, SUM(ISNULL(不合格数, 0)) AS 终检不合格数合计
					   FROM     dbo.YL_质量检验_质检记录 AS YL_质量检验_质检记录_1
					   WHERE   (质检类型 = ''终检'')
					   GROUP BY 计划号) AS zj_终检数量 ON v.订单号 = zj_终检数量.计划号
	WHERE   
				    单据状态 is null 
	 '
    
    if(@订单号 != '') 
        set @selectStr = @selectStr + ' and v.订单号 = ''' + @订单号 + ''''
	if(@属性='机加') 
        set @selectStr = @selectStr + ' and ([自制件属性] = ''机加件'') '
    else if(@属性='装配') 
        set @selectStr = @selectStr + ' and [自制件属性] like ''%装配%'' '
	set @selectStr = @selectStr + 'GROUP BY v.订单号 
	HAVING 
		MIN(CASE WHEN v.Expr1 IS NULL THEN 0 ELSE 1 END) = 1
		AND MAX(终检不合格数合计) + MAX(终检合格数合计) + MAX(不合格数合计) = MAX(计划数量)
		AND max(ISNULL(v.入库数量, 0)) = max(ISNULL(zj_终检数量.终检合格数合计, 0)) ORDER BY v.订单号'
end
else
begin
    -- 原有查询逻辑保持不变
    set @selectStr='
    SELECT top 100 
       v.订单编号,
       MAX(物料描述) as 产品名称,
       MAX(物料编号) as 产品编码,
       MAX(入库数量) as 入库数量,
       MAX(合同号) as 合同号,
       MAX(终检不合格数合计) as 终检不合格数合计,
       MAX(终检合格数合计) as 终检合格数合计,
       MAX(计划数量) as 计划数量,
       MAX(确认状态) as 确认状态,
       MAX(单据状态) as 单据状态
    FROM [dbo].[MES_接口_生产计划] AS v
    LEFT JOIN (
        SELECT 
            计划号,
            SUM(ISNULL(合格数, 0)) AS 终检合格数合计,
            SUM(ISNULL(不合格数, 0)) AS 终检不合格数合计
        FROM dbo.YL_质量检验_质检记录
        WHERE 质检类型 = ''终检''
        GROUP BY 计划号
    ) zj_终检数量 ON v.[订单编号] = zj_终检数量.计划号'
  
    if(@订单号 != '') 
        set @selectStrWhere = @selectStrWhere + ' and v.[订单编号] = ''' + @订单号 + ''''
    if(@单据状态='SAP未关闭') 
        set @selectStrWhere = @selectStrWhere + ' and ([单据状态] = ''已关闭'') '
    if(@单据状态='已关闭') 
        set @selectStrWhere = @selectStrWhere + ' and ([单据状态] = ''已关闭'' or [单据状态] = ''已取消'') '
    else if(@单据状态='未关闭') 
        set @selectStrWhere = @selectStrWhere + ' and [单据状态] is null'
    if(@属性='机加') 
        set @selectStrWhere = @selectStrWhere + ' and ([自制件属性] = ''机加件'') '
    else if(@属性='装配') 
        set @selectStrWhere = @selectStrWhere + ' and [自制件属性] like ''%装配%'' '    
    set @selectStrWhere = @selectStrWhere + ' group by v.订单编号'
    set @selectStr = @selectStr + @selectStrWhere

end

print @selectStr
EXEC sp_executesql @selectStr
GO
/****** Object:  StoredProcedure [dbo].[计划排产_生产订单关闭_关闭订单]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[计划排产_生产订单关闭_关闭订单]
@订单号 nvarchar(100) = ''

as
begin
    declare @selectStr nvarchar(4000)
    declare @selectStrWhere nvarchar(4000) = ' WHERE (v.加工工时 > 0 OR v.总时长 > 0) 
      AND v.Expr1 IS NULL  
     '
    
    set @selectStr = '
    SELECT 
       v.订单号,
       MAX(产品名称) as 产品名称,
       MAX(产品编码) as 产品编码,
       MAX(入库数量) as 入库数量,
       MAX(合同号) as 合同号,
       MAX(终检不合格数合计) as 终检不合格数合计,
       MAX(终检合格数合计) as 终检合格数合计,
       MAX(合格数合计) as 合格数合计,
       MAX(不合格数合计) as 不合格数合计,
       MAX(计划数量) as 计划数量,
       min(完成数量)  as 完成数量,
       MAX(确认状态) as 确认状态,
       MAX(单据状态) as 单据状态
    FROM [dbo].[View_生产工时视图] AS v
    LEFT JOIN (
        SELECT 
            TaskAID,
            SUM(ISNULL(合格数, 0)) AS 合格数合计,
            SUM(ISNULL(不合格数, 0)) AS 不合格数合计
        FROM dbo.YL_质量检验_质检记录
        WHERE 质检类型 = ''收检''
        GROUP BY TaskAID
    ) zj_收检 ON v.[TaskAID] = zj_收检.TaskAID 
    LEFT JOIN (
        SELECT 
            TaskAID,
            SUM(ISNULL(合格数, 0)) AS 终检合格数合计,
            SUM(ISNULL(不合格数, 0)) AS 终检不合格数合计
        FROM dbo.YL_质量检验_质检记录
        WHERE 质检类型 = ''终检''
        GROUP BY TaskAID
    ) zj_终检数量 ON v.[TaskAID] = zj_终检数量.TaskAID'   
    
    set @selectStrWhere = @selectStrWhere + ' group by v.订单号'
    set @selectStr = @selectStr + @selectStrWhere
    
    -- 执行原查询，返回结果
    print @selectStr
    
    -- 判断传入的订单号是否在查询结果中
    if @订单号 != ''
    begin
        declare @orderExists int = 0
        
        -- 直接查询订单是否存在，避免使用临时表
        set @selectStrWhere = ' WHERE (v.加工工时 > 0 OR v.总时长 > 0) 
          AND v.Expr1 IS NULL  
          AND v.订单号 = ''' + @订单号 + '''
          group by v.订单号'
        
        set @selectStr = '
        SELECT @orderExists = COUNT(1)
        FROM [dbo].[View_生产工时视图] AS v
        LEFT JOIN (
            SELECT 
                TaskAID,
                SUM(ISNULL(合格数, 0)) AS 合格数合计,
                SUM(ISNULL(不合格数, 0)) AS 不合格数合计
            FROM dbo.YL_质量检验_质检记录
            WHERE 质检类型 = ''收检''
            GROUP BY TaskAID
        ) zj_收检 ON v.[TaskAID] = zj_收检.TaskAID 
        LEFT JOIN (
            SELECT 
                TaskAID,
                SUM(ISNULL(合格数, 0)) AS 终检合格数合计,
                SUM(ISNULL(不合格数, 0)) AS 终检不合格数合计
            FROM dbo.YL_质量检验_质检记录
            WHERE 质检类型 = ''终检''
            GROUP BY TaskAID
        ) zj_终检数量 ON v.[TaskAID] = zj_终检数量.TaskAID
        ' + @selectStrWhere
        
        -- 执行查询判断订单是否存在
        EXEC sp_executesql @selectStr, N'@orderExists int output', @orderExists = @orderExists output
        
        if @orderExists > 0
		begin
             select @订单号 as 订单号, '有工时未校验，关闭失败' as 提示信息,0 as result        
        end
        else
        begin
            update [dbo].[MES_接口_生产计划] 
            set 单据状态 = '已关闭' 
            where 订单编号 = @订单号
            
            if @@ROWCOUNT > 0
                select @订单号 as 订单号, '关闭成功' as 提示信息,1 as result   
            else
                select @订单号 as 订单号, '未找到对应订单，关闭失败' as 提示信息
        end
    end
   
end
GO
/****** Object:  StoredProcedure [dbo].[计划排产_生产订单关闭_确认订单]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		刘帅
-- Create date: 2021-03-26
-- =============================================
create     PROCEDURE [dbo].[计划排产_生产订单关闭_确认订单]
@订单号 int=null
 AS



update [dbo].[MES_接口_生产计划] set 确认状态 = 1  where 订单编号 = @订单号

GO
/****** Object:  StoredProcedure [dbo].[计划排产_外协分组]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


create PROCEDURE [dbo].[计划排产_外协分组] 
@TaskAID int,
@外协分组  NVARCHAR(50)
AS
begin
SET NOCOUNT ON;
    update [dbo].[MES_接口_生产计划_生产任务] set 外协分组 = @外协分组 where AID = @TaskAID
	
end
GO
/****** Object:  StoredProcedure [dbo].[计划排产_重置派工状态]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		赵艳华
-- Create date: 2025-03-30
-- Description:	计划排产、拆分
-- =============================================
CREATE PROCEDURE [dbo].[计划排产_重置派工状态] 
@TaskAID NVARCHAR(MAX)
AS
begin
SET NOCOUNT ON;

        -- 更新打印次数
       DECLARE @Sql NVARCHAR(MAX)
    
    SET @Sql = '
        UPDATE [dbo].[MES_接口_生产计划_生产任务]
        SET 
            [派工状态] = 0,
            [派工时间] = GETDATE(),
            [修改时间] = GETDATE()
        WHERE AID IN (' + @TaskAID + ')'
    
    EXEC sp_executesql @Sql

end
GO
/****** Object:  StoredProcedure [dbo].[计划排产_自制件_日程时间修改]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO





-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[计划排产_自制件_日程时间修改]
	@订单号 int,
	@订单行号 int=0,
	@订单拆分内码 int =0,
	@计划开始时间 nvarchar(50) = '',
	@计划完成时间 nvarchar(50) = ''
AS


update [MES_接口_生产计划_生产任务] set 计划开始时间 = @计划开始时间,计划完成时间 = @计划完成时间 where 订单编号=@订单号 and 订单行号=@订单行号 and 订单拆分内码=@订单拆分内码 and isnull(派工状态,0)=0

GO
/****** Object:  StoredProcedure [dbo].[计算人员工时]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[计算人员工时]
    @TaskAID bigint,
    @RecordAID int,
    @OPName nvarchar(50),
    @开始时间 datetime,
    @结束时间 datetime,
    @总工作秒数 int,
    @合同号 nvarchar(50),
    @订单编号 int,
    @物料编号 nvarchar(50),
    @物料描述 nvarchar(50),
    @工位编号 nvarchar(50),
    @工序名称 nvarchar(50),
    @操作类别 nvarchar(50),
    @系统操作人 nvarchar(50),
    @实际干活人员 NVARCHAR(50) = NULL
AS
BEGIN
    SET NOCOUNT ON;
    
    -- 创建临时表存储计算结果
    declare @人员工时明细表 table (
        人员编号 nvarchar(50),
        人员姓名 nvarchar(50),
        班次名称 nvarchar(50),
        绑定设备数 int,
        班次时长秒数 int,
        重叠秒数 int,
        计算工时秒数 int
    )
    
    -- 获取所有班次配置
    declare @班次表 table (
        班次编号 nvarchar(50),
        班次名称 nvarchar(50),
        开始时间 time,
        结束时间 time,
        班次时长秒数 int
    )
    
    insert into @班次表 (班次编号, 班次名称, 开始时间, 结束时间, 班次时长秒数)
    select 
        b.班次编号,
        b.班次名称,
        b.开始时间,
        b.结束时间,
        DATEDIFF(SECOND, 
            b.开始时间,
            CASE WHEN b.结束时间 < b.开始时间 
                 THEN DATEADD(DAY, 1, CAST(b.结束时间 AS datetime)) 
                 ELSE CAST(b.结束时间 AS datetime) 
            END) as 班次时长秒数
    from [dbo].[班次表] b
    where b.是否删除 = 0
    
    -- 如果班次表中没有数据，插入默认数据
    --if not exists (select 1 from @班次表)
    --begin
    --    insert into @班次表 (班次编号, 班次名称, 开始时间, 结束时间, 班次时长秒数)
    --    values 
    --    ('BC001', '白班', '07:45', '16:30', 8*60*60 + 45*60),  -- 8小时45分钟 = 31500秒
    --    ('BC002', '晚班', '16:30', '00:40', 8*60*60)           -- 8小时 = 28800秒
    --end
    
    -- 获取绑定到该工位的所有人员
    declare @绑定人员表 table (
        人员编号 nvarchar(50),
        人员姓名 nvarchar(50),
        绑定设备数 int
    )
    
    -- =============== 第一步：先获取工位绑定人员（无论是否指定人员） ===============
    INSERT INTO @绑定人员表 (人员编号, 人员姓名, 绑定设备数)
    SELECT distinct 
        a.人员编号,
        ISNULL(c.Personnel_Name, '未知') as 人员姓名,
        (select COUNT(DISTINCT b2.Name) 
         from [dbo].[工位人员绑定表] a2 
         left join [dbo].[MES_资源主数据] b2 on a2.工位号 = b2.VisCode
         where a2.人员编号 = a.人员编号 
           and a2.绑定状态 = 1
           and b2.Name is not NULL) as 绑定设备数
    from [dbo].[工位人员绑定表] a 
    left join [dbo].[MES_资源主数据] b on a.工位号 = b.VisCode 
    left join [dbo].[登录基础数据_人员信息] c on a.人员编号 = c.Personnel_Number
    where a.绑定状态 = 1  
    and b.Name is not NULL  
    and b.Name = @OPName
    
    -- 如果没有绑定人员，尝试获取其他信息
    if not exists (select 1 from @绑定人员表)
    begin
        -- 尝试使用操作人作为默认人员
        insert into @绑定人员表 (人员编号, 人员姓名, 绑定设备数)
        values ('0000', @系统操作人, 1)
    end
    
    -- =============== 第二步：如果指定了人员，额外增加 ===============
    IF (@实际干活人员 IS NOT NULL AND LTRIM(RTRIM(@实际干活人员)) != '')
    BEGIN
        DECLARE @指定人员编号 NVARCHAR(50), @指定人员姓名 NVARCHAR(50)
        
        -- 通过编号查找人员
        SELECT @指定人员姓名 = Personnel_Name 
        FROM [登录基础数据_人员信息] 
        WHERE Personnel_Number = @实际干活人员
        
        IF (@指定人员姓名 IS NOT NULL)
        BEGIN
            SET @指定人员编号 = @实际干活人员
        END
        ELSE
        BEGIN
            -- 可能是传的姓名，通过姓名查找
            SELECT TOP 1 
                @指定人员编号 = Personnel_Number,
                @指定人员姓名 = Personnel_Name
            FROM [登录基础数据_人员信息] 
            WHERE Personnel_Name = @实际干活人员
            
            IF (@指定人员编号 IS NULL)
            BEGIN
                -- 都没找到，直接使用传入值
                SET @指定人员编号 = @实际干活人员
                SET @指定人员姓名 = @实际干活人员
            END
        END
        
        -- 检查指定人员是否已经在绑定人员表中
        DECLARE @人员已存在 BIT = 0
        
        SELECT @人员已存在 = 1 
        FROM @绑定人员表 
        WHERE 人员编号 = @指定人员编号 OR 人员姓名 = @指定人员姓名
        
        IF (@人员已存在 = 0)
        BEGIN
            -- 如果不存在，则额外插入指定人员，绑定设备数=1
            INSERT INTO @绑定人员表 (人员编号, 人员姓名, 绑定设备数)
            VALUES (@指定人员编号, @指定人员姓名, 1)
        END
        ELSE
        BEGIN
            -- 如果已经存在，可以更新绑定设备数为1
            UPDATE @绑定人员表 
            SET 绑定设备数 = 1 
            WHERE 人员编号 = @指定人员编号 OR 人员姓名 = @指定人员姓名
        END
    END
    
    -- =============== 第三步：为每个人计算所有班次的工时 ===============
    -- 为每个人计算所有班次的工时（使用秒为单位）
    insert into @人员工时明细表 (人员编号, 人员姓名, 绑定设备数, 班次名称, 班次时长秒数, 重叠秒数, 计算工时秒数)
    select 
        p.人员编号,
        p.人员姓名,
        p.绑定设备数,
        b.班次名称,
        b.班次时长秒数,
        -- 计算班次重叠秒数
        dbo.计算班次重叠秒数(@开始时间, @结束时间, b.开始时间, b.结束时间) as 重叠秒数,
        0 as 计算工时秒数  -- 初始值
    from @绑定人员表 p
    cross join @班次表 b
    
    -- =============== 第四步：关键修改 - 根据是否指定人员进行班次过滤 ===============
    
    -- 获取日期部分（用于班次人员绑定）
    DECLARE @日期 DATE = CAST(@开始时间 AS DATE)
    
    -- 创建临时表存储需要删除的记录
    DECLARE @需要删除的表 TABLE (
        人员编号 NVARCHAR(50),
        班次名称 NVARCHAR(50)
    )
    
    -- 过滤逻辑
    IF (@实际干活人员 IS NOT NULL AND LTRIM(RTRIM(@实际干活人员)) != '')
    BEGIN
        -- 情况1：指定了人员
        
        -- 获取指定人员的班次绑定信息
        DECLARE @指定人员班次表 TABLE (
            班次编号 NVARCHAR(50),
            班次名称 NVARCHAR(50)
        )
        
        -- 获取指定人员的班次绑定
        INSERT INTO @指定人员班次表 (班次编号, 班次名称)
        SELECT DISTINCT 
            bb.班次编号,
            b.班次名称
        FROM [dbo].[班次人员绑定表] bb
        INNER JOIN [dbo].[班次表] b ON bb.班次编号 = b.班次编号
        WHERE bb.人员编号 = @实际干活人员
          AND bb.是否删除 = 0
          AND bb.绑定时间 <= @开始时间  -- 绑定时间在开始时间之前
        
        -- 对于工位绑定人员：必须满足两个条件
        -- 1. 在班次人员绑定表中（属于该班次）
        -- 2. 工作时间与班次时间有重叠
        -- 先标记需要删除的记录
        INSERT INTO @需要删除的表 (人员编号, 班次名称)
        SELECT t.人员编号, t.班次名称
        FROM @人员工时明细表 t
        WHERE (t.人员编号 != @实际干活人员 AND t.人员姓名 != @实际干活人员)  -- 工位绑定人员
          AND (
              -- 条件1：人员不在班次人员绑定表中
              NOT EXISTS (
                  SELECT 1 FROM [dbo].[班次人员绑定表] bb
                  INNER JOIN [dbo].[班次表] b ON bb.班次编号 = b.班次编号
                  WHERE bb.人员编号 = t.人员编号
                    AND b.班次名称 = t.班次名称
                    AND bb.是否删除 = 0
                    AND bb.绑定时间 <= @开始时间
              )
              -- 条件2：时间不重叠
              OR t.重叠秒数 <= 0
          )
        
        -- 删除标记的记录
        DELETE t
        FROM @人员工时明细表 t
        INNER JOIN @需要删除的表 d ON t.人员编号 = d.人员编号 AND t.班次名称 = d.班次名称
        
        -- 清空临时表
        DELETE FROM @需要删除的表
        
        -- 检查指定人员是否有班次绑定
        DECLARE @指定人员有班次绑定 BIT = 0
        
        SELECT @指定人员有班次绑定 = 1 
        FROM @指定人员班次表 
        WHERE EXISTS (SELECT 1 FROM @指定人员班次表)
        
        IF (@指定人员有班次绑定 = 1)
        BEGIN
            -- 指定人员在班次绑定表中：删除不在其班次的记录
            INSERT INTO @需要删除的表 (人员编号, 班次名称)
            SELECT t.人员编号, t.班次名称
            FROM @人员工时明细表 t
            WHERE (t.人员编号 = @实际干活人员 OR t.人员姓名 = @实际干活人员)
              AND t.班次名称 NOT IN (SELECT 班次名称 FROM @指定人员班次表)
            
            DELETE t
            FROM @人员工时明细表 t
            INNER JOIN @需要删除的表 d ON t.人员编号 = d.人员编号 AND t.班次名称 = d.班次名称
        END
        ELSE
        BEGIN
            -- 指定人员不在班次绑定表中：保留一条记录（如果重叠秒数=0，设为1秒）
            -- 先删除所有指定人员的记录
            DELETE FROM @人员工时明细表
            WHERE (人员编号 = @实际干活人员 OR 人员姓名 = @实际干活人员)
            
            -- 插入一条记录（选择工作时间最长的班次）
            INSERT INTO @人员工时明细表 (人员编号, 人员姓名, 绑定设备数, 班次名称, 班次时长秒数, 重叠秒数, 计算工时秒数)
            SELECT TOP 1
                p.人员编号,
                p.人员姓名,
                p.绑定设备数,
                b.班次名称,
                b.班次时长秒数,
                -- 如果完全不在班次内，给1秒的最小工时
                CASE 
                    WHEN dbo.计算班次重叠秒数(@开始时间, @结束时间, b.开始时间, b.结束时间) > 0
                    THEN dbo.计算班次重叠秒数(@开始时间, @结束时间, b.开始时间, b.结束时间)
                    ELSE 1
                END as 重叠秒数,
                0 as 计算工时秒数
            FROM @绑定人员表 p
            CROSS JOIN @班次表 b
            WHERE (p.人员编号 = @实际干活人员 OR p.人员姓名 = @实际干活人员)
            ORDER BY dbo.计算班次重叠秒数(@开始时间, @结束时间, b.开始时间, b.结束时间) DESC
        END
    END
    ELSE
    BEGIN
        -- 情况2：没有指定人员
        -- 标记需要删除的记录
        INSERT INTO @需要删除的表 (人员编号, 班次名称)
        SELECT t.人员编号, t.班次名称
        FROM @人员工时明细表 t
        WHERE NOT EXISTS (
            SELECT 1 FROM [dbo].[班次人员绑定表] bb
            INNER JOIN [dbo].[班次表] b ON bb.班次编号 = b.班次编号
            WHERE bb.人员编号 = t.人员编号
              AND b.班次名称 = t.班次名称
              AND bb.是否删除 = 0
              AND bb.绑定时间 <= @开始时间
        )
        OR t.重叠秒数 <= 0
        
        -- 删除标记的记录
        DELETE t
        FROM @人员工时明细表 t
        INNER JOIN @需要删除的表 d ON t.人员编号 = d.人员编号 AND t.班次名称 = d.班次名称
    END
    
    -- =============== 第五步：计算每个人的工时 ===============
    --update t
    --set 计算工时秒数 = 
    --    CASE 
    --        WHEN 绑定设备数 > 0 
    --        THEN CAST(重叠秒数 AS decimal(10,2)) / 绑定设备数
    --        ELSE 0
    --    END
    --from @人员工时明细表 t
	update t
    set 计算工时秒数 = CAST(重叠秒数 AS decimal(10,2))
    from @人员工时明细表 t
    
    -- =============== 第六步：插入工时记录 ===============
    declare @开始时间格式化 nvarchar(50) = CONVERT(nvarchar(19), @开始时间, 120)
    declare @结束时间格式化 nvarchar(50) = CONVERT(nvarchar(19), @结束时间, 120)
    declare @总工作时间分钟 decimal(10,2) = CAST(@总工作秒数 as decimal(10,2)) / 60.0
    
    INSERT INTO [dbo].[YL_加工中心_操作记录表] (
        [操作类别编号],
        [操作类别],
        [工序名称],
        [工位名称],
        [操作人],
        [合同号],
        [订单编号],
        [物料编号],
        [物料描述],
        [TaskAID],
        [开始时间],
        [结束时间],
        [总时长],
        [操作描述]
    )
    SELECT 
        4 AS 操作类别编号,
        @操作类别,
        @工序名称,
        @OPName AS 工位名称,
        人员姓名 AS 操作人,
        @合同号,
        @订单编号,
        @物料编号,
        @物料描述,
        @TaskAID,
        @开始时间,
        @结束时间,
        计算工时秒数 AS 总时长,
        CASE 
            WHEN 人员编号 = @实际干活人员 OR 人员姓名 = @实际干活人员
            THEN '[指定人员]'
            ELSE ''
        END + '人员工时分摊记录：班次=' + 班次名称 + ', 绑定设备=' + CAST(绑定设备数 AS NVARCHAR(10)) AS 操作描述      
    FROM @人员工时明细表
    WHERE 计算工时秒数 > 0
    
    -- =============== 第七步：构建并更新操作描述 ===============
    -- 构建人员工时描述信息
    declare @人员工时描述 nvarchar(max) = '人员工时计算: '
    
    -- 如果找到了人员，添加详细信息
    if exists (select 1 from @人员工时明细表)
    begin
        -- 添加汇总信息
        set @人员工时描述 = @人员工时描述 + 
            '开始:' + @开始时间格式化 + 
            ',结束:' + @结束时间格式化 + 
            ',总时长:' + CAST(@总工作秒数 as nvarchar(20)) + '秒(' + CAST(@总工作时间分钟 as nvarchar(20)) + '分钟);'
        
        -- 添加每个人详细信息
        DECLARE @人员详情 NVARCHAR(MAX) = ''
        
        SELECT @人员详情 = @人员详情 + 
            CASE 
                WHEN 人员编号 = @实际干活人员 OR 人员姓名 = @实际干活人员
                THEN '[指定人员-' + 人员姓名 + ':班次' + 班次名称 + 
                     ',绑定' + CAST(绑定设备数 as nvarchar(10)) + '台' +
                     ',重叠' + CAST(重叠秒数 as nvarchar(10)) + '秒' +
                     ',计算' + CAST(计算工时秒数 as nvarchar(10)) + '秒(' + 
                     CAST(CAST(计算工时秒数 as decimal(10,2))/60.0 as nvarchar(20)) + '分钟)]; '
                ELSE '[' + 人员姓名 + ':班次' + 班次名称 + 
                     ',绑定' + CAST(绑定设备数 as nvarchar(10)) + '台' +
                     ',重叠' + CAST(重叠秒数 as nvarchar(10)) + '秒' +
                     ',计算' + CAST(计算工时秒数 as nvarchar(10)) + '秒(' + 
                     CAST(CAST(计算工时秒数 as decimal(10,2))/60.0 as nvarchar(20)) + '分钟)]; '
            END
        FROM @人员工时明细表
        
        SET @人员工时描述 = @人员工时描述 + @人员详情
        
        -- 添加汇总信息
        declare @总计算工时秒数 decimal(10,2) = 0
        declare @总计算工时分钟 decimal(10,2) = 0
        declare @参与人数 int = 0
        declare @指定人员数 int = 0
        
        SELECT 
            @总计算工时秒数 = SUM(CAST(计算工时秒数 as decimal(10,2))),
            @总计算工时分钟 = SUM(CAST(计算工时秒数 as decimal(10,2))) / 60.0,
            @参与人数 = COUNT(DISTINCT 人员编号),
            @指定人员数 = COUNT(DISTINCT CASE 
                WHEN 人员编号 = @实际干活人员 OR 人员姓名 = @实际干活人员 
                THEN 人员编号 
                ELSE NULL 
            END)
        FROM @人员工时明细表
        
        SET @人员工时描述 = @人员工时描述 + 
            '汇总:共' + CAST(@参与人数 as nvarchar(10)) + '人' +
            CASE WHEN @指定人员数 > 0 THEN '(含' + CAST(@指定人员数 as nvarchar(10)) + '名指定人员)' ELSE '' END +
            ',总工时' + CAST(@总计算工时秒数 as nvarchar(20)) + '秒(' + CAST(@总计算工时分钟 as nvarchar(20)) + '分钟);'
    end
    else
    begin
        set @人员工时描述 = @人员工时描述 + '无绑定人员信息或人员不在工作班次内;'
    end
    
    -- 更新主记录的操作描述，添加人员工时信息
    update [YL_加工中心_操作记录表] 
    set 操作描述 = 
        CASE 
            WHEN 操作描述 IS NULL OR 操作描述 = '' 
            THEN @人员工时描述
            ELSE 操作描述 + ' ' + @人员工时描述
        END
    where AID = @RecordAID
    
    -- 调试信息
    print '人员工时计算完成: ' + @人员工时描述
    
    -- =============== 第八步：返回计算结果（可选，用于调试） ===============
    select 
        人员编号,
        人员姓名,
        班次名称,
        绑定设备数,
        班次时长秒数,
        重叠秒数,
        计算工时秒数,
        CAST(计算工时秒数 as decimal(10,2)) / 60.0 as 计算工时分钟,
        CASE 
            WHEN 人员编号 = @实际干活人员 OR 人员姓名 = @实际干活人员
            THEN '指定人员'
            ELSE '工位绑定人员'
        END as 人员类型
    from @人员工时明细表
    order by 
        CASE 
            WHEN 人员编号 = @实际干活人员 OR 人员姓名 = @实际干活人员
            THEN 0  -- 指定人员排前面
            ELSE 1
        END,
        计算工时秒数 desc
    
END
GO
/****** Object:  StoredProcedure [dbo].[加工中心_收检_读取收检记录]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




-- 工时校验_保存校验记录
CREATE PROCEDURE [dbo].[加工中心_收检_读取收检记录]
    @TaskAID int
   
AS
declare @已检验数量 int
declare @完成数量 int
declare @上序合格数 int
declare @订单编号 int=-1
declare @订单行号 int=-1
select @订单编号=[订单编号],@订单行号 = 订单行号 FROM [View_生产订单_MES] where TaskAID=@TaskAID
	select @已检验数量 = sum(检验数量) OVER() from YL_质量检验_质检记录 where TaskAID = @TaskAID and 质检类型 = '收检'
	select @完成数量 = 完成数量 from [dbo].[MES_接口_生产计划_生产任务] where AID = @TaskAID
	SELECT @上序合格数 =  SUM(ISNULL(合格数, 0)) 
          FROM [dbo].[YL_质量检验_质检记录] qc
          INNER JOIN [View_生产订单_MES] vt ON qc.TaskAID = vt.TaskAID
          WHERE vt.[订单编号] = @订单编号 
            AND vt.[订单行号] = @订单行号-1
			AND qc.检测类型编号 = '6'
select isnull(@已检验数量,0),isnull(@完成数量,0),isnull(@上序合格数,0),@订单行号
GO
/****** Object:  StoredProcedure [dbo].[加工中心_修改工时_保存修改记录]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



-- 工时校验_保存校验记录
CREATE PROCEDURE [dbo].[加工中心_修改工时_保存修改记录]
    @TaskAID bigint,
    @开始时间 datetime,
    @结束时间 datetime,
    @工时 int,
    @操作人 nvarchar(50),
    @最后编辑人 nvarchar(50)
AS
BEGIN 
-- 更新记录表
update [dbo].[YL_加工中心_操作记录表] 
set 最后编辑时间 = GETDATE(),最后编辑人 = @最后编辑人,实际工时 = @工时, 开始时间 = @开始时间, 结束时间 = @结束时间 
where AID = @TaskAID
END
GO
/****** Object:  StoredProcedure [dbo].[加工中心_异常工时_获取操作记录列表]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



-- 工时校验_获取操作记录列表
CREATE PROCEDURE [dbo].[加工中心_异常工时_获取操作记录列表]
    @操作人 nvarchar(50)
AS
BEGIN
    SET NOCOUNT ON;
    
    -- 获取未校验的记录（不存在于校验表中的记录）
   
    BEGIN
        SELECT 
            o.AID,
            o.操作类别编号,
            o.操作类别,
            o.阶段标识,
            o.工序名称,
            o.工位编号,
            o.工位名称,
            o.操作人 as 指派对象,
            o.合同号,
            o.订单编号 as 订单号,
            o.物料编号 as 产品编码,
            o.物料描述 as 产品名称,
            o.操作数值,
            o.操作内容,
            o.操作描述,
            o.TaskAID,
            o.开始时间,
            o.结束时间,
            o.实际工时 as 加工工时,
			o.暂停总时长 as 暂停工时,
			o.总时长 as 总工时,
            o.报工日期,
            o.已报工,
            o.不装配,
            CASE WHEN c.AID IS NOT NULL THEN 1 ELSE 0 END as 已校验,
            o.最后编辑人,
            o.最后编辑时间
        FROM [dbo].[YL_加工中心_操作记录表] o
        LEFT JOIN [dbo].[生产管理_工时校验_校验工时表] c ON o.AID = c.报工记录id
        WHERE c.AID IS NULL  and  o.操作人 = @操作人  and o.操作类别编号 in  ('8','9') -- 未校验的记录
    END
    
    
END
GO
/****** Object:  StoredProcedure [dbo].[加急订单_加急明细查询]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE      PROCEDURE [dbo].[加急订单_加急明细查询]

@物料编号 nvarchar(50) = null
with recompile
AS
--SELECT * from [dbo].[MES_接口_生产计划]
--where 物料编号 = @物料编号 
--and 加急状态 = 1
SELECT docentry as 订单编号 , itemcode as 物料编号, 加急数量  from  SAP.SBO_YL.dbo.ubt_OPKL_UrgentMaterials_ALL
where itemcode = @物料编号 
GO
/****** Object:  StoredProcedure [dbo].[看板_右上合同看板_表格_查询]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

create PROCEDURE [dbo].[看板_右上合同看板_表格_查询]
AS
BEGIN
  SET NOCOUNT ON;
  
  -- 合同看板数据暂无，返回空结果集保持前端一致
  SELECT TOP 0
    '' AS 交货期,
    '' AS 合同号,
    '' AS 产品名称,
    '' AS 工艺,
    '' AS 采购,
    '' AS 加工,
    '' AS 备料,
    '' AS 装配,
    '' AS 成品入库,
    '' AS 合同发货
END
GO
/****** Object:  StoredProcedure [dbo].[看板_右下质量看板_表格_查询]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[看板_右下质量看板_表格_查询]
AS
BEGIN
  SET NOCOUNT ON;
  
  -- 质量看板数据暂无，返回空结果集保持前端一致
  SELECT TOP 10 * from [dbo].[YL_质量检验_质检记录] where 质检类型 = '终检' order by 检测时间 desc
END
GO
/****** Object:  StoredProcedure [dbo].[看板_右下质量看板_饼图_查询]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

create PROCEDURE [dbo].[看板_右下质量看板_饼图_查询]
AS
BEGIN
  SET NOCOUNT ON;
  
  -- 质量饼图数据暂无，返回默认值保持前端一致
  SELECT '无' AS 缺陷类型, 0 AS 数量
END
GO
/****** Object:  StoredProcedure [dbo].[看板_中间实时OEE数据展示_查询]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

create PROCEDURE [dbo].[看板_中间实时OEE数据展示_查询]
AS
BEGIN
  SET NOCOUNT ON;
  
  CREATE TABLE #t (
    产品名称 NVARCHAR(50),
    OEE NVARCHAR(50),
    时间利用率 NVARCHAR(50),
    性能利用率 NVARCHAR(50),
    合格率 NVARCHAR(50),
    设备状态 NVARCHAR(50),
    进度 NVARCHAR(50)
  )
  INSERT INTO #t 
  VALUES ('加工中心1', '85.6', '88.2', '78.9', '98.3', '正常', '45'),
         ('加工中心2', '82.6', '82.2', '83.9', '93.3', '正常', '63')
  SELECT * FROM #t
  DROP TABLE #t
END
GO
/****** Object:  StoredProcedure [dbo].[看板_中间主体订单_表格_查询]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[看板_中间主体订单_表格_查询]
AS
BEGIN
  SET NOCOUNT ON;

  SELECT TOP 100
    t.合同号 AS 内部合同号,
    '' AS 签订日期,
    '' AS 交货日期,
    t.工艺部,
    CAST(0 AS DECIMAL(5,1)) AS 采购部,
    ISNULL(lp.生产进度, 0) AS 生产部,
    t.装配部,
	t.最大计划完成,
	t.最小计划开始
  FROM (
    SELECT 
      订单编号,
      MAX(合同号) AS 合同号,
      MAX(计划完成) AS 最大计划完成,
	  min(计划开始) AS 最小计划开始,
      ISNULL(CAST(ROUND(
        SUM(CASE WHEN 生产工艺 = 1 THEN 1.0 ELSE 0 END) / NULLIF(COUNT(*), 0) * 100
      , 1) AS DECIMAL(5,1)), 0) AS 工艺部,
      -- 装配部：自制件属性包含“装配”的工序完成进度
      ISNULL(CAST(ROUND(
        SUM(CASE WHEN 自制件属性 LIKE '%装配%' THEN ISNULL(完成数量, 0) ELSE 0 END) * 100.0 / 
        NULLIF(SUM(CASE WHEN 自制件属性 LIKE '%装配%' THEN ISNULL(指派数量, 0) ELSE 0 END), 0)
      , 1) AS DECIMAL(5,1)), 0) AS 装配部
    FROM View_生产订单_MES
    WHERE 合同号 IS NOT NULL AND 合同号 <> ''
    GROUP BY 订单编号
  ) t
  OUTER APPLY (
    SELECT TOP 1
      CAST(ROUND(
        SUM(ISNULL(完成数量, 0)) * 100.0 / NULLIF(SUM(ISNULL(指派数量, 0)), 0)
      , 1) AS DECIMAL(5,1)) AS 生产进度
    FROM View_生产订单_MES
    WHERE 订单编号 = t.订单编号
      AND 顺序编号 = (SELECT MAX(顺序编号) FROM View_生产订单_MES WHERE 订单编号 = t.订单编号)
    GROUP BY 顺序编号
  ) lp
  ORDER BY t.最大计划完成 DESC
END
GO
/****** Object:  StoredProcedure [dbo].[看板_中间主体订单详情_表格_查询]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

create PROCEDURE [dbo].[看板_中间主体订单详情_表格_查询]
  @合同号 NVARCHAR(50) = NULL
AS
BEGIN
  SET NOCOUNT ON;

  SELECT
    物料描述 AS 名称,
    物料编号 AS 规格型号,
    自制件属性 AS 零件属性,
    指派数量 AS 额定数量,
    ISNULL(指派数量, 0) AS 总需求,
    0 AS 库存数量,
    0 AS 待出数量,
    0 AS 可用库存,
    0 AS 满足情况,
    0 AS 占用数量,
    0 AS 在购数量,
    0 AS 满足二,
    0 AS 满足三,
    物料编号 AS 产品编码,
    合同号
  FROM View_生产订单_MES
  WHERE 合同号 = @合同号
  ORDER BY 顺序编号
END
GO
/****** Object:  StoredProcedure [dbo].[看板_主页六个关键数据_查询]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [dbo].[看板_主页六个关键数据_查询]
AS
BEGIN
  SET NOCOUNT ON;
  
  DECLARE @nowDateTime DATETIME = GETDATE()
  
  -- 计算6个关键指标
  DECLARE @当前计划 FLOAT = 0
  SELECT @当前计划 = ISNULL(SUM(ISNULL(指派数量, 0)), 0)
  FROM View_生产订单_MES 
  WHERE YEAR(计划完成) = YEAR(@nowDateTime) AND MONTH(计划完成) = MONTH(@nowDateTime)
  
  DECLARE @当前产量 FLOAT = 0
  SELECT @当前产量 = ISNULL(SUM(ISNULL(完成数量, 0)), 0)
  FROM View_生产订单_MES 
  WHERE YEAR(计划完成) = YEAR(@nowDateTime) AND MONTH(计划完成) = MONTH(@nowDateTime)
  
  DECLARE @计划完成 FLOAT = 0
  IF @当前计划 > 0
    SET @计划完成 = ROUND((@当前产量 / @当前计划) * 100, 1)
  
  DECLARE @工时消耗 FLOAT = 0
  SELECT @工时消耗 = ISNULL(SUM(ISNULL(加工工时, 0)), 0)
  FROM View_生产工时视图 
  WHERE YEAR(报工日期) = YEAR(@nowDateTime) AND MONTH(报工日期) = MONTH(@nowDateTime)
  
  DECLARE @齐套订单数 FLOAT = 0, @总订单数 FLOAT = 0, @当前齐套率 FLOAT = 0
  SELECT @齐套订单数 = COUNT(DISTINCT CASE WHEN 齐套 = 1 THEN 订单编号 END),
         @总订单数 = COUNT(DISTINCT 订单编号)
  FROM View_生产订单_MES
  WHERE YEAR(计划完成) = YEAR(@nowDateTime) AND MONTH(计划完成) = MONTH(@nowDateTime)
  IF @总订单数 > 0
    SET @当前齐套率 = ROUND((@齐套订单数 / @总订单数) * 100, 1)
  
  DECLARE @当前合格率 FLOAT = 0, @不合格总数 FLOAT = 0
  SELECT @不合格总数 = ISNULL(SUM(ISNULL(不合格数量, 0)), 0)
  FROM View_生产订单_MES
  WHERE YEAR(计划完成) = YEAR(@nowDateTime) AND MONTH(计划完成) = MONTH(@nowDateTime)
  IF @当前产量 > 0
    SET @当前合格率 = ROUND(((@当前产量 - @不合格总数) / @当前产量) * 100, 1)
  ELSE
    SET @当前合格率 = 100

  -- 统一格式返回所有数据
  SELECT Zone, Sort, TagName, TagValue, TagUnit, Icon, color FROM (
    -- 生产信息 6项
    SELECT '生产' AS Zone, 1 AS Sort, '当前计划' AS TagName, CAST(@当前计划 AS NVARCHAR(50)) AS TagValue, '台' AS TagUnit, 'AssemblyPlan' AS Icon, '#0678b4' AS color
    UNION ALL SELECT '生产', 2, '当前产量', CAST(@当前产量 AS NVARCHAR(50)), '台', 'ManufacturingExecution', '#68b720'
    UNION ALL SELECT '生产', 3, '计划完成', CAST(@计划完成 AS NVARCHAR(50)), '%', 'ProductionCheck', '#e97378'
    UNION ALL SELECT '生产', 4, '工时消耗', CAST(@工时消耗 AS NVARCHAR(50)), 'h', 'ManHourStatistics', '#9d6dd5'
    UNION ALL SELECT '生产', 5, '齐套率', CAST(@当前齐套率 AS NVARCHAR(50)), '%', 'GroupMatching', '#dc7e86'
    UNION ALL SELECT '生产', 6, '合格率', CAST(@当前合格率 AS NVARCHAR(50)), '%', 'QualityBasicData', '#fafc80'
    -- 环境监测 8项
    UNION ALL SELECT '环境', 1, '二氧化碳', '420', 'ppm', 'CloudData', ''
    UNION ALL SELECT '环境', 2, '甲醛', '0.08', 'mg/m³', 'SafetyMargin', ''
    UNION ALL SELECT '环境', 3, 'TVOC', '0.15', 'mg/m³', 'QualityBasicData', ''
    UNION ALL SELECT '环境', 4, 'PM2.5', '35', 'μg/m³', 'OqcInformation', ''
    UNION ALL SELECT '环境', 5, 'PM10', '65', 'μg/m³', 'OqcInformation', ''
    UNION ALL SELECT '环境', 6, '温度', '24.5', '℃', 'MeasurementRangeMaintenance', ''
    UNION ALL SELECT '环境', 7, '湿度', '45', '%RH', 'Maintenancebasicequipmentinformation', ''
    UNION ALL SELECT '环境', 8, '噪声', '55', 'dB', 'EquipmentAlarmStatistics', ''
    -- 水 3项
    UNION ALL SELECT '水', 1, '瞬时流量', '2.5', 'm³/min', 'MaterialPull', ''
    UNION ALL SELECT '水', 2, '累计流量', '1580', 'm³', 'InventoryManagement', ''
    UNION ALL SELECT '水', 3, '压力', '0.35', 'Mpa', 'EquipmentStatusMonitoring', ''
    -- 电 4项
    UNION ALL SELECT '电', 1, '电压A', '380', 'V', 'ElectricalComponentParameters', ''
    UNION ALL SELECT '电', 2, '电压B', '382', 'V', 'ElectricalComponentParameters', ''
    UNION ALL SELECT '电', 3, '电压C', '378', 'V', 'ElectricalComponentParameters', ''
    UNION ALL SELECT '电', 4, '电能', '1250', 'kwh', 'RealTimeStatusEquipment', ''
    -- 气 4项
    UNION ALL SELECT '气', 1, '瞬时流量', '15.8', 'm³/min', 'MaterialPull', ''
    UNION ALL SELECT '气', 2, '累计流量', '8520', 'm³', 'InventoryManagement', ''
    UNION ALL SELECT '气', 3, '温度', '22', '℃', 'MeasurementRangeMaintenance', ''
    UNION ALL SELECT '气', 4, '压力', '0.65', 'Mpa', 'EquipmentStatusMonitoring', ''
  ) t
  ORDER BY 
    CASE Zone WHEN '生产' THEN 0 WHEN '环境' THEN 1 WHEN '水' THEN 2 WHEN '电' THEN 3 WHEN '气' THEN 4 END,
    Sort
END
GO
/****** Object:  StoredProcedure [dbo].[看板_左上订单看板_表格_查询]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

create PROCEDURE [dbo].[看板_左上订单看板_表格_查询]
AS
BEGIN
  SET NOCOUNT ON;
  
  SELECT TOP 50
    t.合同号 AS 内部合同号,
    CONVERT(nvarchar(10), t.最大计划完成, 23) AS 交货日期,
    t.工艺部,
    CAST(0 AS DECIMAL(5,1)) AS 采购部,
    ISNULL(lp.生产进度, 0) AS 生产部,
    t.装配部
  FROM (
    SELECT 
      订单编号,
      MAX(合同号) AS 合同号,
      MAX(计划完成) AS 最大计划完成,
      -- 工艺部：有生产工艺的任务占比
      ISNULL(CAST(ROUND(
        SUM(CASE WHEN 生产工艺 = 1 THEN 1.0 ELSE 0 END) / NULLIF(COUNT(*), 0) * 100
      , 1) AS DECIMAL(5,1)), 0) AS 工艺部,
      -- 装配部：自制件属性包含"装配"的工序完成进度
      ISNULL(CAST(ROUND(
        SUM(CASE WHEN 自制件属性 LIKE '%装配%' THEN ISNULL(完成数量, 0) ELSE 0 END) * 100.0 / 
        NULLIF(SUM(CASE WHEN 自制件属性 LIKE '%装配%' THEN ISNULL(指派数量, 0) ELSE 0 END), 0)
      , 1) AS DECIMAL(5,1)), 0) AS 装配部
    FROM View_生产订单_MES
    WHERE 合同号 IS NOT NULL AND 合同号 <> ''
    GROUP BY 订单编号
  ) t
  OUTER APPLY (
    -- 生产部：取当前订单中顺序编号最大的那道工序的进度
    SELECT TOP 1
      CAST(ROUND(
        SUM(ISNULL(完成数量, 0)) * 100.0 / NULLIF(SUM(ISNULL(指派数量, 0)), 0)
      , 1) AS DECIMAL(5,1)) AS 生产进度
    FROM View_生产订单_MES
    WHERE 订单编号 = t.订单编号
      AND 顺序编号 = (SELECT MAX(顺序编号) FROM View_生产订单_MES WHERE 订单编号 = t.订单编号)
    GROUP BY 顺序编号
  ) lp
  ORDER BY t.最大计划完成 DESC
END
GO
/****** Object:  StoredProcedure [dbo].[看板_左上计划执行情况_曲线_查询]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

create PROCEDURE [dbo].[看板_左上计划执行情况_曲线_查询]
AS
BEGIN
  SET NOCOUNT ON;

  DECLARE @date DATE = CAST(GETDATE() AS DATE)

  SELECT 
    RIGHT(CONVERT(nvarchar(10), MAX(计划完成), 23), 5) AS 交货日期,
    ISNULL(CAST(ROUND(AVG(
      CASE WHEN 生产工艺 = 1 THEN 100.0 ELSE 0 END
    ), 1) AS DECIMAL(5,1)), 0) AS 工艺部,
    CAST(0 AS DECIMAL(5,1)) AS 采购部,
    ISNULL(CAST(ROUND(AVG(
      CASE WHEN ISNULL(指派数量, 0) > 0 THEN ISNULL(完成数量, 0) * 100.0 / 指派数量 ELSE 0 END
    ), 1) AS DECIMAL(5,1)), 0) AS 生产部,
    -- 装配部：自制件属性包含“装配”的工序完成进度
    ISNULL(CAST(ROUND(AVG(
      CASE WHEN 自制件属性 LIKE '%装配%' AND ISNULL(指派数量, 0) > 0 
        THEN ISNULL(完成数量, 0) * 100.0 / 指派数量 
        ELSE NULL END
    ), 1) AS DECIMAL(5,1)), 0) AS 装配部,
    COUNT(1) AS 条数
  FROM View_生产订单_MES
  WHERE 合同号 IS NOT NULL AND 合同号 <> ''
    AND CAST(计划完成 AS DATE) >= DATEADD(DAY, -10, @date)
    AND CAST(计划完成 AS DATE) <= @date
  GROUP BY CAST(计划完成 AS DATE)
  ORDER BY CAST(计划完成 AS DATE)
END
GO
/****** Object:  StoredProcedure [dbo].[看板_左下未完成看板_表格_查询]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

create PROCEDURE [dbo].[看板_左下未完成看板_表格_查询]
AS
BEGIN
  SET NOCOUNT ON;

  SELECT TOP 50
    m.合同号 AS 内部合同号,
    m.物料描述 AS 零件名称,
    CONVERT(nvarchar(10), m.计划完成时间, 23) AS 要求完工日,
    m.工序名称,
    CASE m.自制件属性 
      WHEN '机加件' THEN '自制'
      WHEN '机械装配' THEN '自制'
      WHEN '电气装配' THEN '自制'
      ELSE ISNULL(m.自制件属性, '自制')
    END AS 性质,
    CAST(ISNULL(h.完工工时合计, 0) AS DECIMAL(10,1)) AS 完工工时,
    CAST(
      CASE 
        WHEN ISNULL(p.标准工时, 0) - ISNULL(h.完工工时合计, 0) < 0 THEN 0
        ELSE ISNULL(p.标准工时, 0) - ISNULL(h.完工工时合计, 0) 
      END AS DECIMAL(10,1)
    ) AS 未完工工时
  FROM View_生产订单_MES m
  LEFT JOIN (
    -- 按TaskAID汇总已完成工时
    SELECT TaskAID, SUM(ISNULL(加工工时, 0)) AS 完工工时合计
    FROM View_生产工时视图
    GROUP BY TaskAID
  ) h ON m.TaskAID = h.TaskAID
  LEFT JOIN View_生产工艺视图 p ON m.订单编号 = p.订单编号 AND m.顺序编号 = p.工艺顺序
  WHERE m.任务状态 IN (0, 1, 2)  -- 未完工状态
    AND m.合同号 IS NOT NULL AND m.合同号 <> ''
  ORDER BY m.计划完成时间 DESC
END
GO
/****** Object:  StoredProcedure [dbo].[看板_左中装配看板_表格_查询]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

create PROCEDURE [dbo].[看板_左中装配看板_表格_查询]
AS
BEGIN
  SET NOCOUNT ON;

  SELECT TOP 50
    合同号 AS 内部合同号,
    物料描述 AS 产品名称,
    CONVERT(nvarchar(10), ISNULL(要求发货日期, 计划完成), 23) AS 要求发货时间,
    CASE 
      WHEN 发货状态 = '1' THEN '已出库'
      WHEN 发货状态 = '0' THEN '未出库'
      ELSE '未出库'
    END AS 出库状态
  FROM View_生产订单_MES
  WHERE 自制件属性 IN ('机械装配', '电气装配')
    AND 合同号 IS NOT NULL AND 合同号 <> ''
  ORDER BY ISNULL(要求发货日期, 计划完成) DESC
END
GO
/****** Object:  StoredProcedure [dbo].[跨库查询测试]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[跨库查询测试]
as
select * from [ERPTOOL_JY20250826].[dbo].[PDM_订单信息_视图]

GO
/****** Object:  StoredProcedure [dbo].[人员管理_角色信息初始化查询_查询]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE       PROCEDURE [dbo].[人员管理_角色信息初始化查询_查询]

AS



SELECT *
FROM 登录基础数据_角色信息
where [Roles_number] <> 1
GO
/****** Object:  StoredProcedure [dbo].[人员管理_人员信息查询]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

create      PROCEDURE [dbo].[人员管理_人员信息查询]

AS
BEGIN
	  SET NOCOUNT ON;
select * from [dbo].[登录基础数据_管理人员权限视图]

END
GO
/****** Object:  StoredProcedure [dbo].[人员管理_人员信息查询_查询]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE       PROCEDURE [dbo].[人员管理_人员信息查询_查询]

@姓名_check int = null,
@姓名 nvarchar(500) = null,
@角色代码_check int = null,
@角色代码 nvarchar(500) = null,
@PageCurrent 	int,       --要显示的页码
@PageSize   	int,     --每页的大小(记录数)
@PageCount  	int  output,     --总页数
@ItemCount	int  output	--数据总数
AS
BEGIN
	  SET NOCOUNT ON;
declare @tbname		sysname --要分页显示的表名
declare @fieldkey	sysname--用于定位记录的主键(惟一键)字段,只能是单个字段
declare @where		nvarchar(1000)--查询条件
declare @fieldshow	nvarchar(1000)--以逗号分隔的要显示的字段列表,如果不指定,则显示所有字段
declare @fieldOrder	nvarchar(1000) ----以逗号分隔的排序字段列表,可以指定在字段后面指定DESC/ASC  --用于指定排序顺序
declare @a nvarchar(2)

set @where =' 1=1 '
set @tbname = '登录基础数据_管理人员权限视图'
set @fieldkey = ' Personnel_Number '
set @fieldOrder= ' Personnel_Number desc '
set @fieldshow=''
set @a=''''


set @where = @where + ' and  Personnel_Number is not null'
--set @where = @where + ' and Personnel_Number is not null  and Quit =1 '

if(@姓名_check = 1)
	if(@姓名 is not null)
		set @where = @where+' and Personnel_Name like '+substring(@a,1,1)+'%'+@姓名+substring(@a,1,1) + '+'+substring(@a,1,1)+'%'+substring(@a,1,1)

if(@角色代码_check = 1)
	if(@角色代码 is not null)
		set @where = @where+' and Roles_number = '  + CAST(@角色代码 AS NVARCHAR(50))

exec dbo.sp_xt_pagesplit @tbname,@fieldkey,@where,@fieldshow,@fieldOrder,@PageCurrent,@PageSize,@PageCount out,@ItemCount out

END
GO
/****** Object:  StoredProcedure [dbo].[人员管理_人员信息查询_质检部门_查询]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create      PROCEDURE [dbo].[人员管理_人员信息查询_质检部门_查询]

AS
BEGIN
	  SET NOCOUNT ON;
select * from [dbo].[登录基础数据_管理人员权限视图]

END
GO
/****** Object:  StoredProcedure [dbo].[人员管理_人员信息新增_新增]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE                 PROCEDURE [dbo].[人员管理_人员信息新增_新增]

@account nvarchar(50) = null,
@password nvarchar(50) = null,
@Personnel_Name nvarchar(50) = null,
@Roles_number int = null
AS


DECLARE @是否存在 int = 0

if(select count(*) from [登录基础数据_人员信息] where account =@account ) = 0
begin
INSERT INTO [登录基础数据_人员信息]

(account,password,Personnel_Name)
VALUES 
(@account,@password,@Personnel_Name)

declare @Personnel_Number int
select @Personnel_Number = Personnel_Number from [登录基础数据_人员信息]
where account = @account

INSERT INTO [登录基础数据_人员权限角色]

(Personnel_Number,Roles_number)
VALUES 
(@Personnel_Number,@Roles_number)
select '1' as result
return
end
select '2' as result
GO
/****** Object:  StoredProcedure [dbo].[人员管理_人员信息修改_编辑]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE                  PROCEDURE [dbo].[人员管理_人员信息修改_编辑]

@Personnel_Number int = null,
@account nvarchar(50) = null,
@password nvarchar(50) = null,
@Personnel_Name nvarchar(50) = null,
@Roles_number int = null
AS

UPDATE [dbo].[登录基础数据_人员信息]
SET
account  = @account ,password = @password, Personnel_Name = @Personnel_Name
where Personnel_Number = @Personnel_Number

UPDATE [dbo].[登录基础数据_人员权限角色]
SET
Roles_number  = @Roles_number
where Personnel_Number = @Personnel_Number
GO
/****** Object:  StoredProcedure [dbo].[人员管理_人员信息修改_删除]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE          PROCEDURE [dbo].[人员管理_人员信息修改_删除]

@Personnel_Number int = null

AS
if(@Personnel_Number = 1)return
UPDATE [dbo].[登录基础数据_人员信息]
SET
[Quit]  = 0 
where Personnel_Number = @Personnel_Number

 delete from [dbo].[登录基础数据_人员权限角色] where Personnel_Number = @Personnel_Number
GO
/****** Object:  StoredProcedure [dbo].[设备管理_设备数据_工位信息_查询]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:		刘帅
-- Create date: 2021-02-26
-- =============================================
CREATE        PROCEDURE [dbo].[设备管理_设备数据_工位信息_查询]



AS

DECLARE @TempTable TABLE (
    工位名称 nvarchar(50),
    工位号 nvarchar(50)
);


insert into @TempTable (工位名称,工位号)values('加3','加3')


select * from @TempTable 
GO
/****** Object:  StoredProcedure [dbo].[设备管理_设备数据_历史查询]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:		刘帅
-- Create date: 2021-02-26
-- =============================================
CREATE        PROCEDURE [dbo].[设备管理_设备数据_历史查询]

@PageCurrent 	int=1,             --要显示的页码
@PageSize   	int  = 20,         --每页的大小(记录数)
@PageCount  	int OUTPUT,        --总页数
@ItemCount	    int OUTPUT,	       --数据总数
@结束时间 nvarchar(50),
@开始时间 nvarchar(50),
@设备名称 nvarchar(50),
@参数名称 nvarchar(50)
AS
declare @tbname		sysname --要分页显示的表名
declare @fieldkey	sysname --用于定位记录的主键(惟一键)字段,只能是单个字段

declare @where	nvarchar(1000) --以逗号分隔的要显示的字段列表,如果不指定,则显示所有字段
declare @fieldshow	nvarchar(1000) --以逗号分隔的要显示的字段列表,如果不指定,则显示所有字段
declare @fieldOrder	nvarchar(1000) ----以逗号分隔的排序字段列表,可以指定在字段后面指定DESC/ASC  --用于指定排序顺序

set @tbname = '历史_设备数据_定时'
set @fieldkey = 'AID'
set @where = ' 1=1 '
set @fieldOrder = ''
set @fieldshow ='[AID]
      ,[在线状态]
      ,[创建时间]
      ,[设备代码]
      ,[工位号]
      ,[变量类型代码]
      ,[变量名称]
      ,[值]
      ,[TagID]
      ,[DeviceCode]'
-- 安全拼接设备名称（防 SQL 注入）
IF @设备名称 <> N''
BEGIN
    SET @where = @where + N' AND 工位号 = ''' + REPLACE(@设备名称, '''', '''''') + '''';
END
IF @参数名称 <> N''
BEGIN
    SET @where = @where + N' AND 变量名称 LIKE ''%' + REPLACE(@参数名称, '''', '''''') + '%''';
END

SET @开始时间 = @开始时间 + ' 00:00:00.000'
SET @结束时间 = @结束时间 + ' 23:59:59.999'

    SET @where = @where + N' AND 创建时间 >= ''' + REPLACE(@开始时间, '''', '''''') + '''';
    SET @where = @where + N' AND 创建时间 <= ''' + REPLACE(@结束时间, '''', '''''') + '''';




exec [dbo].[sp_xt_pagesplit] @tbname,@fieldkey,@where,@fieldshow,@fieldOrder,@PageCurrent,@PageSize,@PageCount out,@ItemCount out
GO
/****** Object:  StoredProcedure [dbo].[设备管理_设备数据_统计数据查询]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		刘帅
-- Create date: 2021-02-26
-- =============================================
CREATE       PROCEDURE [dbo].[设备管理_设备数据_统计数据查询]


@结束时间 nvarchar(50),
@开始时间 nvarchar(50),
@设备名称 nvarchar(50)
AS

DECLARE @TempTable TABLE (
    设备名称 nvarchar(50),
    参数名称 nvarchar(50),
    参数值 nvarchar(50),
    数据类型 int -- 1是需要查询历史数据的
);


set @开始时间 = @开始时间 + ' 00:00:00.000'
set @结束时间 = @结束时间 + ' 23:59:59.999'

declare @开机时刻 nvarchar(50)
select top 1 @开机时刻 = convert(varchar(19),创建时间, 121) from 历史_工位设备状态每分钟记录 where [工位号] = @设备名称 and 创建时间 >= @开始时间 and 创建时间 <= @结束时间 and 设备状态 = 1 order by 创建时间

declare @停机时长 int = 0 -- 分钟
select @停机时长 = count(1) from 历史_工位设备状态每分钟记录 where [工位号] = @设备名称 and 创建时间 >= @开始时间 and 创建时间 <= @结束时间 and 设备状态 = 0

declare @报警时长 int = 0 -- 分钟
select @报警时长 = count(1) from 历史_工位设备状态每分钟记录 where [工位号] = @设备名称 and 创建时间 >= @开始时间 and 创建时间 <= @结束时间 and 设备状态 = 2

declare @关机时长 int = 0 -- 分钟
select @关机时长 = count(1) from 历史_工位设备状态每分钟记录 where [工位号] = @设备名称 and 创建时间 >= @开始时间 and 创建时间 <= @结束时间 and 设备状态 = -1

declare @程序时长 int = 0 -- 分钟
select @程序时长 = sum(循环时间) from [YL_设备管理_工时记录] where 指派对象 = @设备名称 and 采集时间 >= @开始时间 and 采集时间 <= @结束时间 --group by 循环时间


insert into @TempTable (设备名称,参数名称,参数值,数据类型)values(@设备名称,'开机时刻', @开机时刻, 0)
insert into @TempTable (设备名称,参数名称,参数值,数据类型)values(@设备名称,'停机时长', @停机时长, 1)
insert into @TempTable (设备名称,参数名称,参数值,数据类型)values(@设备名称,'关机时长', @关机时长, 1)
insert into @TempTable (设备名称,参数名称,参数值,数据类型)values(@设备名称,'报警时长', @报警时长, 1)
insert into @TempTable (设备名称,参数名称,参数值,数据类型)values(@设备名称,'程序时长', @程序时长, 2)


select * from @TempTable 
GO
/****** Object:  StoredProcedure [dbo].[设备管理_设备数据_统计数据查询_通过类型]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:		刘帅
-- Create date: 2021-02-26
-- =============================================
CREATE        PROCEDURE [dbo].[设备管理_设备数据_统计数据查询_通过类型]


@结束时间 nvarchar(50),
@开始时间 nvarchar(50),
@设备名称 nvarchar(50),
@参数名称 nvarchar(50),
@数据类型 int = 0
AS

SET @开始时间 = @开始时间 + ' 00:00:00.000'
SET @结束时间 = @结束时间 + ' 23:59:59.999'


if(@数据类型 = 1)
begin
  declare @设备状态 int = -999
  declare @状态名称 nvarchar(50) = '未知'
  if(@参数名称 = '开机时刻') begin set @设备状态 = 0 set @状态名称='开机' end
  if(@参数名称 = '停机时长') begin set @设备状态 = 0 set @状态名称='停机' end
  if(@参数名称 = '报警时长') begin set @设备状态 = 2 set @状态名称='报警' end
  if(@参数名称 = '关机时长') begin set @设备状态 = -1 set @状态名称='关机' end

  select 工位号,设备状态,@状态名称 as 状态名称,convert(varchar(16),创建时间, 121) as 创建时间 from 历史_工位设备状态每分钟记录 where [工位号] = @设备名称 and 创建时间 >= @开始时间 and 创建时间 <= @结束时间 and 设备状态 = @设备状态 order by 创建时间

end

if(@数据类型 = 2)
begin
    select * from [YL_设备管理_工时记录] where 指派对象 = @设备名称 and 采集时间 >= @开始时间 and 采集时间 <= @结束时间 order by 采集时间
end
GO
/****** Object:  StoredProcedure [dbo].[设备管理_设备数据查询]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		刘帅
-- Create date: 2021-02-26
-- =============================================
CREATE        PROCEDURE [dbo].[设备管理_设备数据查询]

--@PageCurrent 	int=1,             --要显示的页码
--@PageSize   	int  = 20,         --每页的大小(记录数)
--@PageCount  	int OUTPUT,        --总页数
--@ItemCount	    int OUTPUT,	       --数据总数
@设备名称 nvarchar(50),
@参数名称 nvarchar(50)
AS
--declare @tbname		sysname --要分页显示的表名
--declare @fieldkey	sysname --用于定位记录的主键(惟一键)字段,只能是单个字段
		--查询条件
--declare @fieldshow	nvarchar(1000) --以逗号分隔的要显示的字段列表,如果不指定,则显示所有字段
--declare @fieldOrder	nvarchar(1000) ----以逗号分隔的排序字段列表,可以指定在字段后面指定DESC/ASC  --用于指定排序顺序
--declare @GroupBy nvarchar(1000)




DECLARE @where NVARCHAR(4000) = N' WHERE 1=1 ';
DECLARE @selectStr NVARCHAR(MAX);

-- 安全拼接设备名称（防 SQL 注入）
IF @设备名称 <> N''
BEGIN
    SET @where = @where + N' AND Zone = ''' + REPLACE(@设备名称, '''', '''''') + '''';
END
IF @参数名称 <> N''
BEGIN
    SET @where = @where + N' AND TagName LIKE ''%' + REPLACE(@参数名称, '''', '''''') + '%''';
END
-- 构建查询：将 TagValue 直接替换为语义化字符串
SET @selectStr = N'
SELECT 
    [AID],
    [CreateTime],
    [UpdateTime],
    [Zone],
    [Sort],
    [TagID],
    [TagName],
    CASE 
        WHEN [TagName] = N''操作模式'' THEN
            CASE TRY_CAST([TagValue] AS INT)
                WHEN 1 THEN N''自动''
                WHEN 3 THEN N''EDIT（编辑模式）''
                WHEN 0 THEN N''MDI（手动数据输入模式）''
                WHEN 10 THEN N''REMOTE（远程模式）''
                WHEN 9 THEN N''REF（参考点返回模式 / 回零模式）''
                WHEN 5 THEN N''JOG（手动连续进给模式 / 点动模式）''
                WHEN 8 THEN N''INC（增量进给模式 / 步进模式）''
                ELSE CAST([TagValue] AS NVARCHAR(500))
            END
        WHEN [TagName] = N''设备状态'' THEN
            CASE TRY_CAST([TagValue] AS INT)
                WHEN -1 THEN N''关机''
                WHEN 0 THEN N''待机''
                WHEN 1 THEN N''运行''
                WHEN 2 THEN N''报警''
                ELSE CAST([TagValue] AS NVARCHAR(500))
            END
        ELSE CAST([TagValue] AS NVARCHAR(500))
    END AS [TagValue],  -- 合并后的字段
    [TagUnit]
FROM [dbo].[CaChe_Var]';

-- 拼接 WHERE 条件
SET @selectStr = @selectStr + @where;

-- 调试
PRINT @selectStr;

-- 执行
EXEC sp_executesql @selectStr;
--SET @tbname = '[dbo].[CaChe_Var]'
--SET @fieldkey = 'AID'
--SET @where = '1=1'
--SET @fieldshow = ''
--IF @设备名称 <> ''
--    SET @where = @where + 'TagName = ''@设备名称'''
--exec [dbo].[sp_xt_pagesplit] @tbname,@fieldkey,@where,@fieldshow,@fieldOrder,@PageCurrent,@PageSize,@PageCount out,@ItemCount out
GO
/****** Object:  StoredProcedure [dbo].[设备管理_设备信息_编辑]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:		刘帅
-- Create date: 2021-03-26
-- update 李显
-- date 09-03
-- =============================================
CREATE        PROCEDURE [dbo].[设备管理_设备信息_编辑]
@设备流水号 int=null,
@设备名称 nvarchar(50)=null,
@设备类型 nvarchar(50)=null,
@设备型号 nvarchar(50)=null
--@加工工艺 int=null,
--@点检类型 int=null,
--@工位 nvarchar(50)=null,
--@原工位 nvarchar(50)=null,
--@工时单价 float=null,
--@月设备加工能力 float=null
 AS

update 基础数据_设备工位点检表 set 设备名称=@设备名称,设备型号=@设备型号,设备类型 = @设备类型 where 设备流水号 = @设备流水号
--update 基础数据_设备工位点检表 set 设备名称=@设备名称,设备型号=@设备型号,工位号=@工位,点检表类型=@点检类型 where 设备流水号 = @设备流水号
--update 设备管理_基础表_设备工艺绑定 set 工艺编号=@加工工艺,月设备加工能力=@月设备加工能力,工时单价=@工时单价 where 设备流水号 = @设备流水号

--if @原工位 <> @工位
--begin
   --update MES_机加工MES_实时监控信息表 set 终端编号 = @工位 where 终端编号 = @原工位
   --update MES_工作站_设备状态表 set 设备号 = @工位 where 设备号 = @原工位
   --update MES_机加工MES_设备数据采集_工位信息_基础表 set 工位号 = @工位 where 工位号 = @原工位
--end
GO
/****** Object:  StoredProcedure [dbo].[设备管理_设备信息_查询]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		刘帅
-- Create date: 2021-02-26
-- =============================================
CREATE        PROCEDURE [dbo].[设备管理_设备信息_查询]
@设备名称_check bit = null,
@设备名称 nvarchar(50)=null,
@设备类型_check bit = null,
@设备类型 int =null
--@工位_check bit = null,
--@工位 nvarchar(50) = null

 AS
 
declare @selectStr nvarchar(4000)
declare @selectStrWhere nvarchar(4000)

--set @selectStr =
--'select * from 设备管理_设备信息_视图 '
set @selectStr =
'select *,[dbo].[YL_基础表_数据字典].词条名称 as 设备类型名称  
from 基础数据_设备工位点检表 
left join [dbo].[YL_基础表_数据字典] 
on 基础数据_设备工位点检表.设备类型 = [dbo].[YL_基础表_数据字典].AID '

set @selectStrWhere = 'where 1 = 1 '

if(@设备名称_check = 1)
	set @selectStrWhere = @selectStrWhere+' and 设备名称 like + ''%'' + @设备名称 + ''%''  '
if(@设备类型_check = 1)
	set @selectStrWhere = @selectStrWhere+' and 基础数据_设备工位点检表.设备类型 = @设备类型'

--set @selectStr = @selectStr+@selectStrWhere + ' order by 工位号 '
set @selectStr = @selectStr+@selectStrWhere
--EXEC sp_executesql @selectStr,N'@设备名称 nvarchar(50),@工位 nvarchar(50) ',
--@设备名称,@工位
EXEC sp_executesql @selectStr,N'@设备名称 nvarchar(50) ',@设备类型
GO
/****** Object:  StoredProcedure [dbo].[设备管理_设备信息_删除]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		刘帅
-- Create date: 2021-03-26
-- =============================================
CREATE        PROCEDURE [dbo].[设备管理_设备信息_删除]
@设备流水号 int=null
 AS

--declare @工位 nvarchar(50)
--select @工位=工位号 from 基础数据_设备工位点检表 where 设备流水号 = @设备流水号

delete from 基础数据_设备工位点检表 where 设备流水号 = @设备流水号
--delete from 设备管理_基础表_设备工艺绑定 where 设备流水号 = @设备流水号

--delete from MES_机加工MES_实时监控信息表 where 终端编号 = @工位
--delete from MES_工作站_设备状态表 where 设备号 = @工位
--delete from MES_机加工MES_设备数据采集_工位信息_基础表 where 工位号 = @工位
GO
/****** Object:  StoredProcedure [dbo].[设备管理_设备信息_增加]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:		刘帅
-- Create date: 2021-03-26
--	update 李显
-- date 09-03
-- =============================================
CREATE        PROCEDURE [dbo].[设备管理_设备信息_增加]
@设备名称 nvarchar(50)=null,
@设备类型 nvarchar(50)=null,
@设备型号 nvarchar(50)=null
--@加工工艺 int=null,
--@点检类型 int=null,
--@工位 nvarchar(50)=null,
--@工时单价 float=null,
--@月设备加工能力 float=null
 AS

--declare @设备流水号 int
--insert into 基础数据_设备工位点检表(设备名称,设备型号,工位号,点检表类型)values(@设备名称,@设备型号,@工位,@点检类型)
insert into 基础数据_设备工位点检表(设备名称,设备型号,设备类型)values(@设备名称,@设备型号,@设备类型)
--set @设备流水号 = @@IDENTITY
--insert into 设备管理_基础表_设备工艺绑定(设备流水号,工艺编号,月设备加工能力,工时单价)values(@设备流水号,@加工工艺,@月设备加工能力,@工时单价)
--if (select COUNT(*) from MES_机加工MES_实时监控信息表 where 终端编号=@工位) = 0
--BEGIN
   --insert MES_机加工MES_实时监控信息表(终端编号,工艺计划流水号,工序流水号,设备名称,班次类型)
   --values(@工位,0,0,@设备名称,11)
--END
--if (select COUNT(*) from MES_工作站_设备状态表 where 设备号=@工位) = 0
--BEGIN
   --insert MES_工作站_设备状态表(设备号,设备状态,设备状态解释)
   --values(@工位,0,'0：空闲1:等待接收加工件2:加工过程中3:加工完成4：取消加工5：插入加工6：暂停加工')
--END
--if (select COUNT(*) from MES_机加工MES_设备数据采集_工位信息_基础表 where 工位号=@工位) = 0
--BEGIN
   --insert MES_机加工MES_设备数据采集_工位信息_基础表(工位号,状态代码)
   --values(@工位,1)
--END
GO
/****** Object:  StoredProcedure [dbo].[设备管理_设备状态_查询]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		刘帅
-- Create date: 2021-02-26
-- Modify date: 2026-03-28
-- Description:	去掉rn=1限制，增加数据去重功能
-- =============================================
CREATE PROCEDURE [dbo].[设备管理_设备状态_查询]

@设备名称 nvarchar(50) = ''
AS

DECLARE @where NVARCHAR(4000) = N' WHERE 1=1 and isnull(加工状态,0) in (2,4)  ';
DECLARE @selectStr NVARCHAR(MAX);

-- 获取当前时间，判断是否小于16:30
DECLARE @当前时间 DATETIME = GETDATE();
DECLARE @小时 INT = DATEPART(HOUR, @当前时间);
DECLARE @分钟 INT = DATEPART(MINUTE, @当前时间);
DECLARE @时间值 FLOAT = @小时 + @分钟 / 60.0;

-- 【配置项】请根据工厂实际排班修改此处
-- 假设白班早上 08:00 开始，下午 16:30 结束并转入夜班
DECLARE @白班开始阈值 FLOAT = 7.5;  -- 08:00
DECLARE @夜班开始阈值 FLOAT = 16.5; -- 16:30

DECLARE @班次条件 NVARCHAR(100);

-- 逻辑：
-- 1. 时间 >= 16:30 -> 夜班
-- 2. 时间 < 08:00  -> 夜班 (凌晨时段属于前一天开始的夜班)
-- 3. 其他时间     -> 白班
IF @时间值 >= @夜班开始阈值 OR @时间值 < @白班开始阈值
BEGIN
    SET @班次条件 = N' AND d2.班次名称 = N''夜班''';
END
ELSE
BEGIN
    SET @班次条件 = N' AND d2.班次名称 = N''白班''';
END

-- 拼接到原有 WHERE 条件

SET @selectStr = N'
WITH RankedOrders AS (
    SELECT 
        main.TaskAID,
        [订单编号],
        合同号,
        加急总数,
        派工特殊说明,
        [订单拆分内码],
        [订单行号],
        [开工时间],
        [物料编号],
        [物料描述],
        [加急状态],
        [优先级],
        [指派对象编号],
        指派对象,
        [工序名称],
        [二次派工],
        [计划号],
        [指派数量],
        [计划开始时间],
        [计划完成时间],
        [最晚开始时间],
        [收料数量],
        [完成数量],
        齐套,
        发料状态,
        拣配状态,
        任务状态,
        加工状态,
        首检,
        序检,
		(
                   SELECT ISNULL(SUM(ISNULL(a.合格数, 0)), 0)
                   FROM [dbo].[YL_质量检验_质检记录] as a 
                   INNER JOIN [dbo].[MES_接口_生产计划_生产任务] as b ON a.TaskAID = b.AID
                   WHERE b.订单编号 = main.[订单编号] 
                     AND b.订单行号 = main.[订单行号] - 1
					 AND a.检测类型编号 = 6
               ) as 上序合格数,
		ISNULL(zj_收检.合格数合计, 0) AS 收检合格数,
        ISNULL(zj_收检.不合格数合计, 0) AS 收检不合格数,
		STUFF((
			SELECT '','' + d2.人员名称
			FROM [dbo].[View_设备工位人员] d2
			WHERE d2.工位名称 = main.指派对象  ' + @班次条件 + N'
			FOR XML PATH('''')
		), 1, 1, '''') AS 人员名称,
        -- 为每个指派对象按开工时间降序排序
        ROW_NUMBER() OVER (PARTITION BY [指派对象] ORDER BY ISNULL([开工时间], ''1900-01-01'') DESC) AS rn,
        -- 增加一个基于所有字段的去重标识
        ROW_NUMBER() OVER (PARTITION BY 
            [订单编号], [订单行号], [指派对象], [工序名称], [开工时间], [物料编号]
            ORDER BY ISNULL([开工时间], ''1900-01-01'') DESC) AS duplicate_rn
    FROM [View_生产订单_MES] AS main 
	LEFT JOIN (
            SELECT 
                TaskAID,
                SUM(ISNULL(合格数, 0)) AS 合格数合计,
                SUM(ISNULL(不合格数, 0)) AS 不合格数合计
            FROM dbo.YL_质量检验_质检记录
            WHERE 质检类型 = ''收检''
            GROUP BY TaskAID
        ) zj_收检 ON main.TaskAID = zj_收检.TaskAID
	LEFT JOIN [dbo].[View_设备工位人员] as d ON main.指派对象 = d.工位名称
    ' + @where + N'
),
-- 先去重，保留每个重复组中的最新一条记录
DistinctOrders AS (
    SELECT *
    FROM RankedOrders
    WHERE duplicate_rn = 1  -- 去除完全重复的数据
)
SELECT 
    TaskAID,
    [订单编号] as 订单号,
    合同号,
    加急总数,
    派工特殊说明,
    [订单拆分内码],
    [订单行号],
    [开工时间],
    [物料编号] as 零件编码,
    [物料描述] as 零件名称,
    case when isnull([加急状态],0)=1 then ''加急'' else ''否'' end as [加急],
    [优先级] as [优先],
    [指派对象编号],
    指派对象,
    [工序名称],
    [二次派工],
    [计划号],
    isnull([指派数量],0) as 分配数,
    [计划开始时间] as 计划开始,
    [计划完成时间] as 计划完成,
    [最晚开始时间] as 最晚开始,
    isnull([收料数量],0) as 收料,
    isnull([完成数量],0) as 完成数量,
    case 
        when isnull(齐套,0)=1 then ''是'' 
        when isnull(齐套,0)=0 then ''否''
    end as [齐套],
    case 
        when isnull(发料状态,0)=1 then ''发料齐套'' 
        when isnull(发料状态,0)=2 then ''发料缺件''
    end as [发料状态],
    case 
        when isnull(拣配状态,0)=1 then ''已拣配'' 
        when isnull(拣配状态,0)=0 then ''未拣配''
    end as [拣配状态],
    case 
        when isnull(任务状态,0)=4 then ''已完成'' 
        when isnull(任务状态,0)=2 then ''已开工'' 
        when isnull(任务状态,0)=0 then ''待执行'' 
        when isnull(任务状态,0)=1 then ''可执行''
        else '''' 
    end as [任务状态],
    case 
        when isnull(加工状态,0)=2 then ''辅助开始''
        when isnull(加工状态,0)=3 then ''辅助结束''
        when isnull(加工状态,0)=4 then ''开始加工''
        when isnull(加工状态,0)=5 then ''暂停''
        when isnull(加工状态,0)=6 then ''报工''
        else '''' 
    end as [加工状态],
    isnull(加工状态,0) as 加工状态编号,
	上序合格数,
	收检合格数,
	收检不合格数,
	人员名称,
    case when isnull([首检],-1)=1 then ''OK'' when isnull([首检],-1)=0 then ''NG'' else '''' end as [首检],
    case when isnull([序检],-1)=1 then ''OK'' when isnull([序检],-1)=0 then ''NG'' else '''' end as [序检]
FROM DistinctOrders 
left JOIN [dbo].[MES_资源主数据] as s ON DistinctOrders.指派对象 = s.Name
where [指派对象] <> ''外协'' and  [指派对象] not LIKE  ''%装配%''
ORDER BY [指派对象];'

-- 调试
PRINT @selectStr;

-- 执行
EXEC sp_executesql @selectStr;
GO
/****** Object:  StoredProcedure [dbo].[生产管理_]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

create PROCEDURE [dbo].[生产管理_]
@订单号 int=0,
@物料类型 nvarchar(50)='',   --自制件、装配件
@合同号 nvarchar(50)='',
@产品编码  nvarchar(50)='',
@产品名称  nvarchar(50)='',
@工序名称  nvarchar(50)='',
@要求完工日期1  nvarchar(50)='',
@要求完工日期2  nvarchar(50)='',
@计划开始1 nvarchar(50)='',
@计划开始2 nvarchar(50)='',
@计划完成1 nvarchar(50)='',
@计划完成2 nvarchar(50)='',
@排产状态  nvarchar(50)='全部' ,  --全部，已完成、未完成
@指派对象  nvarchar(50)='全部'
AS
BEGIN
    declare @selectStr nvarchar(4000)
    declare @selectStrWhere nvarchar(4000)=' where [物料类型]=''pit_Resource'' '
    
    if(@物料类型='自制件')   --自制件
        set @selectStr='
            SELECT [计划数量订单],isnull(开工时间,0) as 开工时间,isnull(进度,0) as 进度,[TaskAID],[合同号],[订单编号] as 订单号,
            [订单行号],[订单拆分内码] as 拆分内码,[物料编号] as 产品编码,[物料描述] as 产品名称,TRIM(''.'' FROM TRIM(''0'' FROM CAST([计划数量] AS VARCHAR(30)))) AS 计划数量,
            [计划完成] as 要求完工日期,[工序名称],完成数量,v.计划号,收料数量,
            case when [加急状态]=1 then ''加急'' else '''' end as 加急状态,性质,isnull(总工时,0) as 总工时,[占用情况]
            ,[排产状态],[工序计划数量],指派对象编号,指派对象,TRIM(''.'' FROM TRIM(''0'' FROM CAST([指派数量] AS VARCHAR(30)))) AS 指派数量,计划开始时间,计划完成时间,最晚开始时间,
            [派工状态],[外协通知],[优先级],[未完成说明],[派工特殊说明],[最后编辑人],[最后编辑时间],[二次派工],
            case when zj.计划号 is not null then ''是'' else ''否'' end as 终检
            FROM [View_生产订单_MES] v
            LEFT JOIN (
                SELECT DISTINCT 计划号
                FROM dbo.YL_质量检验_质检记录
                WHERE 质检类型 = ''终检''
            ) zj ON v.[订单编号] = zj.计划号'
    --else   --装配件
    --    set @selectStr='
    --        SELECT [计划数量订单],isnull(开工时间,0) as 开工时间,isnull(进度,0) as 进度,[TaskAID],[合同号],[订单编号] as 订单号,
    --        [订单行号],[订单拆分内码] as 拆分内码,[物料编号] as 产品编码,[物料描述] as 产品名称,[计划数量],
    --        '''' as 合同交货期,[计划完成] as 预计齐套时间,''齐'' as 是否齐套,'''' as 齐套检测,''是'' as 齐套锁料,
    --        [计划开始] as 备料日期,0 as 加急状态,isnull(总工时,0) as 总工时,[工序名称],
    --        case when [加急状态]=1 then ''加急'' else '''' end as 加急状态,性质,总工时,[占用情况]
    --        ,[排产状态],[工序计划数量],指派对象编号,指派对象,指派数量,计划开始时间,计划完成时间,最晚开始时间,
    --        [派工状态],[外协通知],[优先级],[未完成说明],[派工特殊说明],[最后编辑人],[最后编辑时间],[二次派工],
    --        case when zj.计划号 is not null then ''是'' else ''否'' end as 终检
    --        FROM [View_生产订单_MES] v
    --        LEFT JOIN (
    --            SELECT DISTINCT 计划号
    --            FROM dbo.YL_质量检验_质检记录
    --            WHERE 质检类型 = ''终检''
    --        ) zj ON v.[订单编号] = zj.计划号'

    if(@订单号>0)set @selectStrWhere=@selectStrWhere + ' and [订单编号]='+Convert(VARCHAR(10),@订单号)
    if(@合同号<>'')set @selectStrWhere=@selectStrWhere + ' and [合同号] like ''%'+@合同号+'%'''
    if(@产品编码<>'')set @selectStrWhere=@selectStrWhere + ' and [物料编号] like ''%'+@产品编码+'%'''
    if(@产品名称<>'')set @selectStrWhere=@selectStrWhere + ' and [物料描述] like ''%'+@产品名称+'%'''
    if(@工序名称<>'')set @selectStrWhere=@selectStrWhere + ' and [工序名称] = '''+@工序名称+''''
    if(@要求完工日期1 <>'')set @selectStrWhere=@selectStrWhere + ' and [计划完成] >= '''+@要求完工日期1+''''
    if(@要求完工日期2 <>'')set @selectStrWhere=@selectStrWhere + ' and [计划完成] <= '''+@要求完工日期2+''''
    if(@计划开始1 <>'')set @selectStrWhere=@selectStrWhere + ' and [计划开始时间] >= '''+@计划开始1+''''
    if(@计划开始2 <>'')set @selectStrWhere=@selectStrWhere + ' and [计划开始时间] <= '''+@计划开始2+''''
    if(@计划完成1 <>'')set @selectStrWhere=@selectStrWhere + ' and [计划完成时间] >= '''+@计划完成1+''''
    if(@计划完成2 <>'')set @selectStrWhere=@selectStrWhere + ' and [计划完成时间] <= '''+@计划完成2+''''
    if(@排产状态='未完成')set @selectStrWhere=@selectStrWhere + ' and isnull([排产状态],0) = 0'
    else if(@排产状态='已完成')set @selectStrWhere=@selectStrWhere + ' and [排产状态] = 1'
    if(@物料类型='自制件') set @selectStrWhere=@selectStrWhere + ' and [不装配] <> ''否'''
    if(@物料类型='装配件') set @selectStrWhere=@selectStrWhere + ' and [不装配] = ''否'''
    if(@指派对象<>'全部') set @selectStrWhere=@selectStrWhere + ' and [指派对象] in (SELECT value FROM STRING_SPLIT('''+@指派对象+''', '',''))'
    
    set @selectStr=@selectStr+@selectStrWhere
    print @selectStr
    EXEC sp_executesql @selectStr
END
GO
/****** Object:  StoredProcedure [dbo].[生产管理_班次管理_班次绑定人员保存]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- 生产管理_班次管理_班次绑定人员保存
CREATE PROCEDURE [dbo].[生产管理_班次管理_班次绑定人员保存]
    @班次编号 NVARCHAR(50),
    @人员编号列表 NVARCHAR(MAX),
    @操作人 NVARCHAR(50)
AS
BEGIN
    SET NOCOUNT ON;
    
    BEGIN TRY
        BEGIN TRANSACTION;
        
        -- 删除该班次原有的绑定关系（软删除）
        UPDATE 班次人员绑定表 
        SET 是否删除 = 1,
            更新时间 = GETDATE(),
            更新人 = @操作人
        WHERE 班次编号 = @班次编号
        AND 是否删除 = 0
        
        -- 如果人员编号列表不为空，插入新的绑定关系
        IF @人员编号列表 IS NOT NULL AND @人员编号列表 != ''
        BEGIN
            -- 将人员编号列表拆分为表
            INSERT INTO 班次人员绑定表 (
                班次编号,
                人员编号,
                绑定时间,
                创建时间,
                创建人,
                更新时间,
                更新人,
                是否删除
            )
            SELECT 
                @班次编号,
                value AS 人员编号,
                GETDATE(),
                GETDATE(),
                @操作人,
                GETDATE(),
                @操作人,
                0
            FROM STRING_SPLIT(@人员编号列表, ',')
            WHERE value IS NOT NULL AND value != ''
        END
        
        SELECT 
            1 AS 执行结果,
            '人员绑定成功' AS 提示信息
        
        COMMIT TRANSACTION;
    END TRY
    BEGIN CATCH
        ROLLBACK TRANSACTION;
        
        SELECT 
            0 AS 执行结果,
            '人员绑定失败：' + ERROR_MESSAGE() AS 提示信息
    END CATCH
END
GO
/****** Object:  StoredProcedure [dbo].[生产管理_班次管理_班次绑定人员查询]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- 生产管理_班次管理_班次绑定人员查询
CREATE PROCEDURE [dbo].[生产管理_班次管理_班次绑定人员查询]
    @班次编号 NVARCHAR(50)
AS
BEGIN
    SET NOCOUNT ON;
    
    SELECT 
        p.Personnel_Number AS 人员编号,
        p.Personnel_Name AS 人员姓名,
        p.account AS 账号,
        p.Roles_Function AS 角色,
        sb.绑定时间
    FROM 班次人员绑定表 sb
    INNER JOIN 登录基础数据_管理人员权限视图 p ON sb.人员编号 = p.Personnel_Number
    WHERE sb.班次编号 = @班次编号
    AND sb.是否删除 = 0
    ORDER BY p.Personnel_Name
END
GO
/****** Object:  StoredProcedure [dbo].[生产管理_班次管理_班次保存]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 生产管理_班次管理_班次保存（增强版）
CREATE PROCEDURE [dbo].[生产管理_班次管理_班次保存]
    @班次编号 NVARCHAR(50),
    @班次名称 NVARCHAR(50),
    @开始时间 NVARCHAR(5),
    @结束时间 NVARCHAR(5),
    @操作人 NVARCHAR(50)
AS
BEGIN
    SET NOCOUNT ON;
    
    DECLARE @执行结果 INT = 1;
    DECLARE @提示信息 NVARCHAR(4000) = '班次保存成功';
    DECLARE @开始时间DT TIME, @结束时间DT TIME;

    BEGIN TRY
        BEGIN TRANSACTION;

        -- 转换时间
        SET @开始时间DT = TRY_CAST(@开始时间 AS TIME);
        SET @结束时间DT = TRY_CAST(@结束时间 AS TIME);

        -- 验证时间格式
        IF @开始时间DT IS NULL OR @结束时间DT IS NULL
        BEGIN
            SET @执行结果 = 0;
            SET @提示信息 = '时间格式不正确，请使用HH:mm格式';
            ROLLBACK TRANSACTION;
            SELECT @执行结果 AS 执行结果, @提示信息 AS 提示信息;
            RETURN;
        END

        -- 检查班次名称重复
        IF EXISTS (SELECT 1 FROM 班次表 WHERE 班次名称 = @班次名称 AND 班次编号 != @班次编号 AND 是否删除 = 0)
        BEGIN
            SET @执行结果 = 0;
            SET @提示信息 = '班次名称已存在，请使用其他名称';
            ROLLBACK TRANSACTION;
            SELECT @执行结果 AS 执行结果, @提示信息 AS 提示信息;
            RETURN;
        END

        -- 检查时间重叠
        --IF EXISTS (
        --    SELECT 1 
        --    FROM 班次表 
        --    WHERE 班次编号 != @班次编号 
        --      AND 是否删除 = 0
        --      AND (
        --        (@开始时间DT BETWEEN 开始时间 AND 结束时间) OR
        --        (@结束时间DT BETWEEN 开始时间 AND 结束时间) OR
        --        (开始时间 BETWEEN @开始时间DT AND @结束时间DT) OR
        --        (结束时间 BETWEEN @开始时间DT AND @结束时间DT)
        --      )
        --)
        --BEGIN
        --    SET @执行结果 = 0;
        --    SET @提示信息 = '班次时间与其他班次重叠，请调整时间';
        --    ROLLBACK TRANSACTION;
        --    SELECT @执行结果 AS 执行结果, @提示信息 AS 提示信息;
        --    RETURN;
        --END

        -- 执行插入或更新
        IF EXISTS (SELECT 1 FROM 班次表 WHERE 班次编号 = @班次编号 AND 是否删除 = 0)
        BEGIN
            UPDATE 班次表 
            SET 
                班次名称 = @班次名称,
                开始时间 = @开始时间DT,
                结束时间 = @结束时间DT,
                更新时间 = GETDATE(),
                更新人 = @操作人
            WHERE 班次编号 = @班次编号;
            
            SET @提示信息 = '班次更新成功';
        END
        ELSE
        BEGIN
            IF EXISTS (SELECT 1 FROM 班次表 WHERE 班次编号 = @班次编号 AND 是否删除 = 1)
            BEGIN
                UPDATE 班次表 
                SET 
                    班次名称 = @班次名称,
                    开始时间 = @开始时间DT,
                    结束时间 = @结束时间DT,
                    是否删除 = 0,
                    更新时间 = GETDATE(),
                    更新人 = @操作人
                WHERE 班次编号 = @班次编号;
            END
            ELSE
            BEGIN
                INSERT INTO 班次表 (
                    班次编号, 班次名称, 开始时间, 结束时间,
                    创建时间, 创建人, 更新时间, 更新人, 是否删除
                ) VALUES (
                    @班次编号, @班次名称, @开始时间DT, @结束时间DT,
                    GETDATE(), @操作人, GETDATE(), @操作人, 0
                );
            END
            SET @提示信息 = '班次保存成功';
        END

        COMMIT TRANSACTION;
        SELECT @执行结果 AS 执行结果, @提示信息 AS 提示信息;

    END TRY
    BEGIN CATCH
        IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION;
        SELECT 
            0 AS 执行结果,
            '班次保存失败：' + ERROR_MESSAGE() AS 提示信息;
    END CATCH
END
GO
/****** Object:  StoredProcedure [dbo].[生产管理_班次管理_班次列表查询]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[生产管理_班次管理_班次列表查询]
AS
BEGIN
    SET NOCOUNT ON;
    
    SELECT 
        班次编号,
        班次名称,
        CONVERT(VARCHAR(5), 开始时间, 108) AS 开始时间,
        CONVERT(VARCHAR(5), 结束时间, 108) AS 结束时间,
        创建时间,
        创建人,
        更新时间,
        更新人
    FROM 班次表
    WHERE 是否删除 = 0
    ORDER BY 开始时间
END
GO
/****** Object:  StoredProcedure [dbo].[生产管理_班次管理_班次删除]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 生产管理_班次管理_班次删除
CREATE PROCEDURE [dbo].[生产管理_班次管理_班次删除]
    @班次编号 NVARCHAR(50),
    @操作人 NVARCHAR(50) = '系统'
AS
BEGIN
    SET NOCOUNT ON;
    
    BEGIN TRY
        BEGIN TRANSACTION;
        
        -- 检查班次是否已被使用
        
        
        IF EXISTS (SELECT 1 FROM 班次人员绑定表 WHERE 班次编号 = @班次编号 AND 是否删除 = 0)
        BEGIN
            SELECT 
                0 AS 执行结果,
                '该班次已绑定人员，请先解除人员绑定' AS 提示信息
            RETURN
        END
        
        -- 软删除班次
        UPDATE 班次表 
        SET 是否删除 = 1,
            更新时间 = GETDATE(),
            更新人 = @操作人
        WHERE 班次编号 = @班次编号
        
        IF @@ROWCOUNT > 0
        BEGIN
            SELECT 
                1 AS 执行结果,
                '班次删除成功' AS 提示信息
        END
        ELSE
        BEGIN
            SELECT 
                0 AS 执行结果,
                '班次不存在或已被删除' AS 提示信息
        END
        
        COMMIT TRANSACTION;
    END TRY
    BEGIN CATCH
        ROLLBACK TRANSACTION;
        
        SELECT 
            0 AS 执行结果,
            '班次删除失败：' + ERROR_MESSAGE() AS 提示信息
    END CATCH
END
GO
/****** Object:  StoredProcedure [dbo].[生产管理_工时查询_工序工时_查询]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[生产管理_工时查询_工序工时_查询]
    @合同号 NVARCHAR(50) = NULL,
    @产品编码 NVARCHAR(100) = NULL,
    @订单号 NVARCHAR(50) = NULL,
    @开始日期 DATE = NULL,
    @结束日期 DATE = NULL,
	@数据条数 int = 100
AS
BEGIN
    SET NOCOUNT ON;

    -- 获取班次信息
    DECLARE @白班开始时间 TIME = '07:45:00'
    DECLARE @白班结束时间 TIME = '16:30:00'
    DECLARE @夜班开始时间 TIME = '16:30:00'
    DECLARE @夜班结束时间 TIME = '00:40:00'
    
    ;WITH 基础数据 AS (
        SELECT top (@数据条数)
            v.*,
            -- 根据班次表判断班次
            CASE 
                WHEN CAST(v.开始时间 AS TIME) >= @白班开始时间 
                     AND CAST(v.开始时间 AS TIME) < @白班结束时间 THEN '白班'
                WHEN CAST(v.开始时间 AS TIME) >= @夜班开始时间 
                     OR CAST(v.开始时间 AS TIME) < @夜班结束时间 THEN '夜班'
                ELSE '其他'
            END AS 班次,
            -- 标记实际工时和辅助工时
            CASE WHEN v.操作内容 = '报工' THEN v.加工工时 ELSE 0 END AS 实际加工工时,
            CASE WHEN v.操作内容 = '辅助结束' THEN v.加工工时 ELSE 0 END AS 辅助加工工时,
            -- 标记报工数量和辅助数量
            CASE WHEN v.操作内容 = '报工' THEN v.操作数值 ELSE 0 END AS 实际报工数量,
            CASE WHEN v.操作内容 = '辅助结束' THEN v.操作数值 ELSE 0 END AS 辅助报工数量,
            -- 关联工艺库获取标准工时（工艺工时）
            p.标准工时 AS 工艺工时
        FROM View_生产工时视图 v
        LEFT JOIN 车间生产管理工艺_零件生产工艺_工艺库 p 
            ON v.订单号 = p.订单编号 
            AND v.订单行号 = p.工艺顺序
        WHERE (@开始日期 IS NULL OR @开始日期 = '' OR v.开始时间  >= @开始日期)
		  AND (@结束日期 IS NULL OR @结束日期 = '' OR v.结束时间  >= @结束日期)
          AND (@合同号 IS NULL OR @合同号 = '' OR v.订单合同号 LIKE '%' + @合同号 + '%')
          AND (@产品编码 IS NULL OR @产品编码 = '' OR v.产品编码 LIKE '%' + @产品编码 + '%')
          AND (@订单号 IS NULL OR @订单号 = '' OR v.订单号 = @订单号 )
          -- 去掉报工时间为0的数据（实际加工工时或辅助加工工时不为0）
          AND (CASE WHEN v.操作内容 = '报工' THEN v.加工工时 ELSE 0 END > 0 
               OR CASE WHEN v.操作内容 = '辅助结束' THEN v.加工工时 ELSE 0 END > 0)
    ),
    -- 获取每个TaskAID对应的任务描述（取第一条记录）
    Task描述 AS (
        SELECT DISTINCT
            TaskAID,
            -- 任务描述：产品名称 + 产品编码 + 工序名称
            ISNULL(产品名称, '') + ' ' + ISNULL(产品编码, '') + ' ' + ISNULL(工序名称, '') + '  序'+ CAST(订单行号 AS VARCHAR(50)) AS 任务描述
        FROM 基础数据
    ),
    -- 第一层：按TaskAID汇总
    TaskAID汇总 AS (
        SELECT 
            b.TaskAID,
            t.任务描述,
            '' AS 工作日期,
            '' AS 班次,
            COUNT(*) AS 报工次数,
            SUM(实际报工数量) AS 实际报工数量,
            SUM(辅助报工数量) AS 辅助报工数量,
            CAST(SUM(实际加工工时) / 60.0 / 60.0 AS DECIMAL(10,1)) AS 实际工时小时,
            CAST(SUM(辅助加工工时) / 60.0 / 60.0 AS DECIMAL(10,1)) AS 辅助工时小时,
            -- 计算平均实际工时（实际加工工时/实际报工数量）
            CASE 
                WHEN SUM(实际报工数量) > 0 
                THEN CAST((SUM(实际加工工时) / 60.0 / 60.0) / SUM(实际报工数量) AS DECIMAL(10,2))
                ELSE 0 
            END AS 平均实际工时,
            -- 计算平均辅助工时（辅助加工工时/辅助报工数量）
            CASE 
                WHEN SUM(辅助报工数量) > 0 
                THEN CAST((SUM(辅助加工工时) / 60.0 / 60.0) / SUM(辅助报工数量) AS DECIMAL(10,2))
                ELSE 0 
            END AS 平均辅助工时,
            -- 工艺工时（取第一条记录的工艺工时）
            MAX(b.工艺工时) AS 工艺工时
        FROM 基础数据 b
        LEFT JOIN Task描述 t ON b.TaskAID = t.TaskAID
        GROUP BY b.TaskAID, t.任务描述
    ),
    -- 第二层：按TaskAID和日期汇总
    日期汇总 AS (
        SELECT 
            b.TaskAID,
            t.任务描述,
            CONVERT(VARCHAR(10), b.开始时间, 120) AS 工作日期,
            '' AS 班次,
            COUNT(*) AS 报工次数,
            SUM(实际报工数量) AS 实际报工数量,
            SUM(辅助报工数量) AS 辅助报工数量,
            CAST(SUM(实际加工工时) / 60.0 / 60.0 AS DECIMAL(10,1)) AS 实际工时小时,
            CAST(SUM(辅助加工工时) / 60.0 / 60.0 AS DECIMAL(10,1)) AS 辅助工时小时,
            -- 计算平均实际工时（实际加工工时/实际报工数量）
            CASE 
                WHEN SUM(实际报工数量) > 0 
                THEN CAST((SUM(实际加工工时) / 60.0 / 60.0) / SUM(实际报工数量) AS DECIMAL(10,2))
                ELSE 0 
            END AS 平均实际工时,
            -- 计算平均辅助工时（辅助加工工时/辅助报工数量）
            CASE 
                WHEN SUM(辅助报工数量) > 0 
                THEN CAST((SUM(辅助加工工时) / 60.0 / 60.0) / SUM(辅助报工数量) AS DECIMAL(10,2))
                ELSE 0 
            END AS 平均辅助工时,
            -- 工艺工时（取该日期第一条记录的工艺工时）
            MAX(b.工艺工时) AS 工艺工时
        FROM 基础数据 b
        LEFT JOIN Task描述 t ON b.TaskAID = t.TaskAID
        GROUP BY b.TaskAID, t.任务描述, CONVERT(VARCHAR(10), b.开始时间, 120)
    ),
    -- 第三层：按TaskAID、日期和班次汇总
    班次汇总 AS (
        SELECT 
            b.TaskAID,
            t.任务描述,
            CONVERT(VARCHAR(10), b.开始时间, 120) AS 工作日期,
            b.班次,
			b.工位名称,
            COUNT(*) AS 报工次数,
            SUM(实际报工数量) AS 实际报工数量,
            SUM(辅助报工数量) AS 辅助报工数量,
            CAST(SUM(实际加工工时) / 60.0 / 60.0 AS DECIMAL(10,1)) AS 实际工时小时,
            CAST(SUM(辅助加工工时) / 60.0 / 60.0 AS DECIMAL(10,1)) AS 辅助工时小时,
            -- 计算平均实际工时（实际加工工时/实际报工数量）
            CASE 
                WHEN SUM(实际报工数量) > 0 
                THEN CAST((SUM(实际加工工时) / 60.0 / 60.0) / SUM(实际报工数量) AS DECIMAL(10,2))
                ELSE 0 
            END AS 平均实际工时,
            -- 计算平均辅助工时（辅助加工工时/辅助报工数量）
            CASE 
                WHEN SUM(辅助报工数量) > 0 
                THEN CAST((SUM(辅助加工工时) / 60.0 / 60.0) / SUM(辅助报工数量) AS DECIMAL(10,2))
                ELSE 0 
            END AS 平均辅助工时,
            -- 工艺工时（取该班次第一条记录的工艺工时）
            MAX(b.工艺工时) AS 工艺工时
        FROM 基础数据 b
        LEFT JOIN Task描述 t ON b.TaskAID = t.TaskAID
        GROUP BY b.TaskAID, t.任务描述, CONVERT(VARCHAR(10), b.开始时间, 120), b.班次,b.工位名称
    )
    
    -- 第一层：TaskAID汇总
    SELECT 
        1 AS [Level],
        TaskAID,
        任务描述 AS taskDescription,
        '' AS dateLabel,
        '' AS shift,
		'' AS 工位名称,
        CAST(实际报工数量 AS VARCHAR(20)) AS reportQty,
        CAST(实际工时小时 AS VARCHAR(20)) AS actualWorkHours,
        CAST(辅助工时小时 AS VARCHAR(20)) AS auxiliaryWorkHours,
        CAST(平均实际工时 AS VARCHAR(20)) AS avgActualWorkHours,
        CAST(平均辅助工时 AS VARCHAR(20)) AS avgAuxiliaryWorkHours,
        CAST(ISNULL(工艺工时, 0) AS VARCHAR(20)) AS processWorkHours,  -- 工艺工时
        '' AS contractNo,
        '' AS orderNo,
        '' AS productCode,
        '' AS productName,
        '' AS processName,
        CAST(报工次数 AS VARCHAR(20)) AS reportCount
    FROM TaskAID汇总
    WHERE 实际工时小时 > 0 OR 辅助工时小时 > 0

    UNION ALL

    -- 第二层：日期汇总
    SELECT 
        2 AS [Level],
        TaskAID,
        任务描述 AS taskDescription,
        工作日期 AS dateLabel,
        '' AS shift,
		'' AS 工位名称,
        CAST(实际报工数量 AS VARCHAR(20)) AS reportQty,
        CAST(实际工时小时 AS VARCHAR(20)) AS actualWorkHours,
        CAST(辅助工时小时 AS VARCHAR(20)) AS auxiliaryWorkHours,
        CAST(平均实际工时 AS VARCHAR(20)) AS avgActualWorkHours,
        CAST(平均辅助工时 AS VARCHAR(20)) AS avgAuxiliaryWorkHours,
        CAST(ISNULL(工艺工时, 0) AS VARCHAR(20)) AS processWorkHours,  -- 工艺工时
        '' AS contractNo,
        '' AS orderNo,
        '' AS productCode,
        '' AS productName,
        '' AS processName,
        CAST(报工次数 AS VARCHAR(20)) AS reportCount
    FROM 日期汇总
    WHERE 实际工时小时 > 0 OR 辅助工时小时 > 0

    UNION ALL

    -- 第三层：班次汇总
    SELECT 
        3 AS [Level],
        TaskAID,
        任务描述 AS taskDescription,
        工作日期 AS dateLabel,
        班次 AS shift,
		工位名称 AS 工位名称,
        CAST(实际报工数量 AS VARCHAR(20)) AS reportQty,
        CAST(实际工时小时 AS VARCHAR(20)) AS actualWorkHours,
        CAST(辅助工时小时 AS VARCHAR(20)) AS auxiliaryWorkHours,
        CAST(平均实际工时 AS VARCHAR(20)) AS avgActualWorkHours,
        CAST(平均辅助工时 AS VARCHAR(20)) AS avgAuxiliaryWorkHours,
        CAST(ISNULL(工艺工时, 0) AS VARCHAR(20)) AS processWorkHours,  -- 工艺工时
        '' AS contractNo,
        '' AS orderNo,
        '' AS productCode,
        '' AS productName,
        '' AS processName,
        CAST(报工次数 AS VARCHAR(20)) AS reportCount
    FROM 班次汇总
    WHERE 实际工时小时 > 0 OR 辅助工时小时 > 0

    ORDER BY TaskAID, dateLabel, shift, [Level]
END
GO
/****** Object:  StoredProcedure [dbo].[生产管理_过程异常管控_发起流程]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:		刘帅
-- Create date: 2021-02-26
-- =============================================
CREATE PROCEDURE [dbo].[生产管理_过程异常管控_发起流程]
    @Title NVARCHAR(200),
    @Description NVARCHAR(MAX),
    @Priority NVARCHAR(20),
    @InitiatorID NVARCHAR(100),
    @InitiatorName NVARCHAR(100),
    @Approvers NVARCHAR(MAX) = NULL, -- JSON格式的审批人列表
    @NewProcessID INT OUTPUT,
	@已关联计划号 INT,
	@零件名称 NVARCHAR(100),
	@零件编号 NVARCHAR(100),
	@工序名称 NVARCHAR(100)
AS
BEGIN
    SET NOCOUNT ON;
    BEGIN TRY
        BEGIN TRANSACTION;

        -- 插入流程主表
        INSERT INTO Processes (Title, Description, Priority, InitiatorID, InitiatorName, Status,已关联计划号,零件名称,零件编号,工序名称)
        VALUES ( @Title, @Description, @Priority, @InitiatorID, @InitiatorName, 'processing',@已关联计划号,@零件名称,@零件编号,@工序名称);
        
        SET @NewProcessID = SCOPE_IDENTITY();
        -- 解析并插入审批节点
        IF @Approvers IS NOT NULL
        BEGIN
            DECLARE @StepNumber INT = 1;
            DECLARE @ApproverTable TABLE (
                NodeType NVARCHAR(50),
                ApproverID NVARCHAR(100),
                ApproverName NVARCHAR(100)
            );

            -- 解析JSON（SQL Server 2016+）
            INSERT INTO @ApproverTable (NodeType, ApproverID, ApproverName)
            SELECT 
                JSON_VALUE(value, '$.type'),
                JSON_VALUE(value, '$.userId'),
                JSON_VALUE(value, '$.userName')
            FROM OPENJSON(@Approvers);

            -- 插入审批节点
            INSERT INTO ProcessNodes (ProcessID, NodeType, NodeName, ApproverID, ApproverName, StepNumber, Status)
            SELECT 
                @NewProcessID,
                NodeType,
                CASE NodeType
                    WHEN 'direct' THEN '直接上级审批'
                    ELSE NodeType
                END,
                ApproverID,
                ApproverName,
                ROW_NUMBER() OVER (ORDER BY (SELECT NULL)),
                'processing'
            FROM @ApproverTable;

            -- 更新总步骤数
            UPDATE Processes 
            SET TotalSteps = (SELECT COUNT(*) FROM ProcessNodes WHERE ProcessID = @NewProcessID),
                CurrentNode = (SELECT TOP 1 NodeName FROM ProcessNodes WHERE ProcessID = @NewProcessID ORDER BY StepNumber)
            WHERE ProcessID = @NewProcessID;
        END

        COMMIT TRANSACTION;
    END TRY
    BEGIN CATCH
        ROLLBACK TRANSACTION;
        THROW;
    END CATCH
END
GO
/****** Object:  StoredProcedure [dbo].[生产管理_获取人员绑定]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[生产管理_获取人员绑定] 
    @操作人ID NVARCHAR(50) = NULL
AS
BEGIN
    SET NOCOUNT ON;

    SELECT 
        m.[name] AS 工位名称
    FROM 
        [dbo].[工位人员绑定表] b
    INNER JOIN 
        [dbo].[MES_资源主数据] m ON m.VisCode = b.工位号
    WHERE 
        b.人员编号 = @操作人ID 
        AND b.绑定状态 = 1;
END
GO
/****** Object:  StoredProcedure [dbo].[生产管理_加工中心_班次信息]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:		<Author,,李显>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
create PROCEDURE [dbo].[生产管理_加工中心_班次信息]

AS
BEGIN
SELECT * FROM [YL_MESDB].[dbo].[View_设备工位人员]
END
GO
/****** Object:  StoredProcedure [dbo].[生产管理_加工中心_辅助自动加班]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 生产管理_加工中心_自动加班（支持多人加班 - 简单版）
create PROCEDURE [dbo].[生产管理_加工中心_辅助自动加班]
    @操作类别 nvarchar(50),
    @订单编号 nvarchar(50),
    @物料编号 nvarchar(50),
    @物料描述 nvarchar(50),
    @工序名称 nvarchar(50),
    @操作人 nvarchar(50),
    @开始时间 datetime,
    @结束时间 datetime,
	@TaskAID nvarchar(2000) = NULL,
	@加班人员 nvarchar(500)
AS
BEGIN
    SET NOCOUNT ON;
    
    BEGIN TRY
        DECLARE @工时 int;
		DECLARE @工位名称 nvarchar(500);
		DECLARE @成功计数 int = 0;
		DECLARE @当前人员 nvarchar(50);
		DECLARE @位置 int;
		DECLARE @人员列表 nvarchar(500) = @加班人员;
		
		-- 获取工位名称
		select @工位名称 = 指派对象 from [dbo].[View_生产订单_MES] where TaskAID = @TaskAID
        
        -- 计算工时（秒）
        SET @工时 = DATEDIFF(SECOND, @开始时间, @结束时间);
        
        -- 开始事务
        BEGIN TRANSACTION;
        
        -- 如果没有指定加班人员，使用操作人
        IF @人员列表 IS NULL OR LEN(@人员列表) = 0
        BEGIN
            SET @人员列表 = @操作人;
        END
        
        -- 创建临时表
        CREATE TABLE #Temp人员 (人员名称 nvarchar(50));
        
        -- 解析字符串并插入临时表
        WHILE LEN(@人员列表) > 0
        BEGIN
            SET @位置 = CHARINDEX(',', @人员列表);
            
            IF @位置 > 0
            BEGIN
                SET @当前人员 = LTRIM(RTRIM(SUBSTRING(@人员列表, 1, @位置 - 1)));
                SET @人员列表 = SUBSTRING(@人员列表, @位置 + 1, LEN(@人员列表));
            END
            ELSE
            BEGIN
                SET @当前人员 = LTRIM(RTRIM(@人员列表));
                SET @人员列表 = '';
            END
            
            IF LEN(@当前人员) > 0
            BEGIN
                INSERT INTO #Temp人员 (人员名称) VALUES (@当前人员);
            END
        END
        
        -- 批量插入所有人员的记录
        INSERT INTO [dbo].[YL_加工中心_操作记录表] (
            操作类别编号, 操作类别, 阶段标识, 工序名称, 工位编号, 
            操作人, 合同号, 订单编号, 物料编号, 物料描述, 操作数值, 操作内容,
            操作描述, 开始时间, 结束时间, 总时长, 报工日期, 已报工, 不装配,
            最后编辑人, 最后编辑时间, TaskAID, 工位名称
        )
        SELECT 
            @操作类别,
            CASE @操作类别 
                WHEN '8' THEN '加班'
                WHEN '9' THEN '异常'
            END,
            0,
            @工序名称,
            '',
            t.人员名称,
            '',
            @订单编号,
            @物料编号,
            @物料描述,
            0,
            '辅助结束',
            '自动加班',
            @开始时间,
            @结束时间,
            @工时,
            CONVERT(date, GETDATE()),
            1,
            '否',
            @操作人,
            GETDATE(),
            @TaskAID,
            @工位名称
        FROM #Temp人员 t;
        
        SET @成功计数 = @@ROWCOUNT;
        
        -- 清理临时表
        DROP TABLE #Temp人员;
        
        -- 提交事务
        COMMIT TRANSACTION;
        
        SELECT '成功' as 结果, 
               '新增操作记录成功，共处理' + CAST(@成功计数 AS nvarchar) + '个人员' as 消息, 
               @成功计数 as 记录数;
        
    END TRY
    BEGIN CATCH
        -- 回滚事务
        IF @@TRANCOUNT > 0
            ROLLBACK TRANSACTION;
            
        -- 清理临时表
        IF OBJECT_ID('tempdb..#Temp人员') IS NOT NULL
            DROP TABLE #Temp人员;
            
        SELECT '错误' as 结果, ERROR_MESSAGE() as 消息, NULL as 记录数;
    END CATCH
END
GO
/****** Object:  StoredProcedure [dbo].[生产管理_加工中心_获取班次信息]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
create PROCEDURE [dbo].[生产管理_加工中心_获取班次信息]
AS
BEGIN
    SET NOCOUNT ON;

   select * from [dbo].[班次表]
		
	
END
GO
/****** Object:  StoredProcedure [dbo].[生产管理_加工中心_获取设备人员]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:		<Author,,李显>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
create PROCEDURE [dbo].[生产管理_加工中心_获取设备人员]
  @指派对象 nvarchar(50),
  @班次 nvarchar(50)
AS
BEGIN
SELECT * FROM [YL_MESDB].[dbo].[View_设备工位人员]  where 工位名称 = @指派对象  and  班次名称 = @班次
END
GO
/****** Object:  StoredProcedure [dbo].[生产管理_加工中心_开始时间]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:		<Author,,李显>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
create PROCEDURE [dbo].[生产管理_加工中心_开始时间]
  @TaskAID nvarchar(50)
AS
BEGIN
select top(1) 
            开始时间
        from [YL_加工中心_操作记录表]
        where TaskAID = @TaskAID 
        order by 结束时间 desc
END
GO
/****** Object:  StoredProcedure [dbo].[生产管理_加工中心_领料物料查询]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO








CREATE     PROCEDURE [dbo].[生产管理_加工中心_领料物料查询]

@编码  nvarchar(50) = null
AS
set nocount on;


select * from [dbo].BOM数据 where 编码  = @编码 


GO
/****** Object:  StoredProcedure [dbo].[生产管理_加工中心_设备是否正在加工]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[生产管理_加工中心_设备是否正在加工]
	@指派对象 NVARCHAR(50)
AS
BEGIN
	select * from [dbo].[MES_接口_生产计划_生产任务] where 指派对象 = @指派对象 AND 加工状态 in ( 2,4 ) 
END
GO
/****** Object:  StoredProcedure [dbo].[生产管理_加工中心_生产发料查询]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO







CREATE     PROCEDURE [dbo].[生产管理_加工中心_生产发料查询]

@生产订单号  nvarchar(50) = null
AS
set nocount on;


select * from SAP.SBO_YL.dbo.UBT_OWOR_OIGE where 生产订单号  = @生产订单号 


GO
/****** Object:  StoredProcedure [dbo].[生产管理_加工中心_退库]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE PROCEDURE [dbo].[生产管理_加工中心_退库]
    @生产订单号 bigint,
    @编码 nvarchar(500),
    @名称 nvarchar(500),
    @数量 float,
    @单位 nvarchar(50),
	@批次信息 nvarchar(50),
    @最后编辑人 nvarchar(50)
AS
BEGIN 
-- 更新记录表
DECLARE @行号 int = 0
select @行号 = max(isnull(行号,0)) from [dbo].[质量检验_质检任务_SAP] where [订单编号] = @生产订单号 and [订单类型] = '202-60'
insert into [dbo].[质量检验_质检任务_SAP] ( [订单编号]
      ,[物料名称]
      ,[物料编码]
      ,[入库数量]
      ,[订单类型]
      ,[同步时间]
      ,[行号]
	  ,[批次信息]
	  ) values( @生产订单号,@名称,@编码,@数量,'202-60',GETDATE(),isnull(@行号+1,0),@批次信息 ) 

END
GO
/****** Object:  StoredProcedure [dbo].[生产管理_加工中心_自动加班]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 生产管理_加工中心_自动加班（支持多人加班 - 简单版）
CREATE PROCEDURE [dbo].[生产管理_加工中心_自动加班]
    @操作类别 nvarchar(50),
    @订单编号 nvarchar(50),
    @物料编号 nvarchar(50),
    @物料描述 nvarchar(50),
    @工序名称 nvarchar(50),
    @操作人 nvarchar(50),
    @开始时间 datetime,
    @结束时间 datetime,
	@TaskAID nvarchar(2000) = NULL,
	@加班人员 nvarchar(500)
AS
BEGIN
    SET NOCOUNT ON;
    
    BEGIN TRY
        DECLARE @工时 int;
		DECLARE @工位名称 nvarchar(500);
		DECLARE @成功计数 int = 0;
		DECLARE @当前人员 nvarchar(50);
		DECLARE @位置 int;
		DECLARE @人员列表 nvarchar(500) = @加班人员;
		
		-- 获取工位名称
		select @工位名称 = 指派对象 from [dbo].[View_生产订单_MES] where TaskAID = @TaskAID
        
        -- 计算工时（秒）
        SET @工时 = DATEDIFF(SECOND, @开始时间, @结束时间);
        
        -- 开始事务
        BEGIN TRANSACTION;
        
        -- 如果没有指定加班人员，使用操作人
        IF @人员列表 IS NULL OR LEN(@人员列表) = 0
        BEGIN
            SET @人员列表 = @操作人;
        END
        
        -- 创建临时表
        CREATE TABLE #Temp人员 (人员名称 nvarchar(50));
        
        -- 解析字符串并插入临时表
        WHILE LEN(@人员列表) > 0
        BEGIN
            SET @位置 = CHARINDEX(',', @人员列表);
            
            IF @位置 > 0
            BEGIN
                SET @当前人员 = LTRIM(RTRIM(SUBSTRING(@人员列表, 1, @位置 - 1)));
                SET @人员列表 = SUBSTRING(@人员列表, @位置 + 1, LEN(@人员列表));
            END
            ELSE
            BEGIN
                SET @当前人员 = LTRIM(RTRIM(@人员列表));
                SET @人员列表 = '';
            END
            
            IF LEN(@当前人员) > 0
            BEGIN
                INSERT INTO #Temp人员 (人员名称) VALUES (@当前人员);
            END
        END
        
        -- 批量插入所有人员的记录
        INSERT INTO [dbo].[YL_加工中心_操作记录表] (
            操作类别编号, 操作类别, 阶段标识, 工序名称, 工位编号, 
            操作人, 合同号, 订单编号, 物料编号, 物料描述, 操作数值, 操作内容,
            操作描述, 开始时间, 结束时间, 总时长, 报工日期, 已报工, 不装配,
            最后编辑人, 最后编辑时间, TaskAID, 工位名称
        )
        SELECT 
            @操作类别,
            CASE @操作类别 
                WHEN '8' THEN '加班'
                WHEN '9' THEN '异常'
            END,
            0,
            @工序名称,
            '',
            t.人员名称,
            '',
            @订单编号,
            @物料编号,
            @物料描述,
            0,
            '',
            '自动加班',
            @开始时间,
            @结束时间,
            @工时,
            CONVERT(date, GETDATE()),
            1,
            '否',
            @操作人,
            GETDATE(),
            @TaskAID,
            @工位名称
        FROM #Temp人员 t;
        
        SET @成功计数 = @@ROWCOUNT;
        
        -- 清理临时表
        DROP TABLE #Temp人员;
        
        -- 提交事务
        COMMIT TRANSACTION;
        
        SELECT '成功' as 结果, 
               '新增操作记录成功，共处理' + CAST(@成功计数 AS nvarchar) + '个人员' as 消息, 
               @成功计数 as 记录数;
        
    END TRY
    BEGIN CATCH
        -- 回滚事务
        IF @@TRANCOUNT > 0
            ROLLBACK TRANSACTION;
            
        -- 清理临时表
        IF OBJECT_ID('tempdb..#Temp人员') IS NOT NULL
            DROP TABLE #Temp人员;
            
        SELECT '错误' as 结果, ERROR_MESSAGE() as 消息, NULL as 记录数;
    END CATCH
END
GO
/****** Object:  StoredProcedure [dbo].[生产管理_加急件管理_更新完成]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[生产管理_加急件管理_更新完成]
    
	@订单号 int

AS
BEGIN
    SET NOCOUNT ON;
    update [dbo].[YL_质量检验_质检记录] set 完成 = 1 where 计划号 = @订单号 and 质检类型 = '终检'
            
END
GO
/****** Object:  StoredProcedure [dbo].[生产管理_加急件管理_更新转至]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[生产管理_加急件管理_更新转至]
    
	@订单号 int

AS
BEGIN
    SET NOCOUNT ON;
    update [dbo].[YL_质量检验_质检记录] set 转至 = 1 where 计划号 = @订单号 and 质检类型 = '终检'
            
END
GO
/****** Object:  StoredProcedure [dbo].[生产管理_加急件管理查询]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- 生产管理_加急件管理查询
CREATE PROCEDURE [dbo].[生产管理_加急件管理查询]
	@转至状态 	int=3 ,
	@完成状态   int=3,
	@合同号 NVARCHAR(100) = '',
    @订单号 NVARCHAR(100) = '',
    @零件编号 NVARCHAR(100) = ''
AS
BEGIN
    SET NOCOUNT ON;
	DECLARE @selectStr NVARCHAR(MAX)
    DECLARE @selectStrWhere NVARCHAR(4000) = ' WHERE [质检类型] = ''终检'' and b.加急总数 > 0 '
	IF @合同号 <> ''
        SET @selectStrWhere = @selectStrWhere + ' AND a.内部合同号 LIKE ''%' + REPLACE(@合同号, '''', '''''') + '%'''

    IF @订单号 <> ''
        SET @selectStrWhere = @selectStrWhere + ' AND a.计划号 = '+@订单号+''

    IF @零件编号 <> ''
        SET @selectStrWhere = @selectStrWhere + ' AND a.零件编码 LIKE ''%' + REPLACE(@零件编号, '''', '''''') + '%'''
    IF @转至状态 <> 3
    BEGIN
        IF @转至状态 = '1'
            SET @selectStrWhere = @selectStrWhere + ' AND 转至 = 1'  -- 转至
        ELSE IF @转至状态 = '2'
            SET @selectStrWhere = @selectStrWhere + ' AND 转至 = 0'  -- 未转至
    END
	IF @完成状态 <> 3
    BEGIN
        IF @完成状态 = '1'
            SET @selectStrWhere = @selectStrWhere + ' AND 完成 = 1'  -- 完成
        ELSE IF @完成状态 = '2'
            SET @selectStrWhere = @selectStrWhere + ' AND 完成 = 0'  -- 未完成
    END
    SET @selectStr = N' select 
		sum(a.不合格数) as 不合格数,
		sum(a.合格数) as 合格数,
		a.内部合同号,
		a.完成,
		a.转至,
		a.计划号,
		a.零件名称,
		a.零件编码,
		sum(a.检验数量) as 检验数量,
		b.加急总数,
		b.加急状态 
		from [dbo].[YL_质量检验_质检记录] AS a
	INNER JOIN [dbo].[View_生产订单_MES] AS b ON a.TaskAID = b.TaskAID  
	'+@selectStrWhere+'
	group by a.内部合同号 ,a.完成,a.转至,a.计划号,
		a.零件名称,
		a.零件编码,
		b.加急总数,
		b.加急状态'
	 -- 添加排序
    --SET @selectStrWhere = @selectStrWhere + ' ORDER BY  计划开始时间 asc'
    
    -- 合并SQL

    
    -- 打印SQL（调试用）
    PRINT @selectStr
    
    -- 执行查询
    EXEC sp_executesql @selectStr
END
GO
/****** Object:  StoredProcedure [dbo].[生产管理_拣配任务_查询]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- 生产管理_加急件管理查询
CREATE PROCEDURE [dbo].[生产管理_拣配任务_查询]
	@合同号 NVARCHAR(100) = '',
    @订单号 NVARCHAR(100) = '',
    @零件编号 NVARCHAR(100) = '',
	@位置 NVARCHAR(100) = ''
AS
BEGIN
    SET NOCOUNT ON;
	DECLARE @selectStr NVARCHAR(MAX)
    DECLARE @selectStrWhere NVARCHAR(4000) = ' WHERE 1=1  '
	IF @合同号 <> ''
        SET @selectStrWhere = @selectStrWhere + ' AND 项目 LIKE ''%' + REPLACE(@合同号, '''', '''''') + '%'''

    IF @订单号 <> ''
        SET @selectStrWhere = @selectStrWhere + ' AND 生产订单号 = '+@订单号+''

    IF @零件编号 <> ''
        SET @selectStrWhere = @selectStrWhere + ' AND 产成品物料编号 LIKE ''%' + REPLACE(@零件编号, '''', '''''') + '%'''
    IF @位置 = 0
        SET @selectStrWhere = @selectStrWhere + ' AND 位置 = ''一楼拣配'''
	IF @位置 = 1
        SET @selectStrWhere = @selectStrWhere + ' AND 位置 = ''二楼拣配'''
	IF @位置 = 2
        SET @selectStrWhere = @selectStrWhere + ' AND 位置 = ''二楼主子机加'''
    SET @selectStr = N' select top 50 * from SAP.SBO_YL.dbo.UBT_MES_TASK_MERGE '
		
	 -- 添加排序
    --SET @selectStrWhere = @selectStrWhere + ' ORDER BY  计划开始时间 asc'
    
    -- 合并SQL
	set @selectStr = @selectStr + @selectStrWhere
    
    -- 打印SQL（调试用）
    PRINT @selectStr
    
    -- 执行查询
    EXEC sp_executesql @selectStr
END
GO
/****** Object:  StoredProcedure [dbo].[生产管理_生产计划跟踪]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE   PROCEDURE [dbo].[生产管理_生产计划跟踪]
    @订单号 int = 0,
    @物料类型 nvarchar(50) = '',   --自制件、装配件
    @合同号 nvarchar(50) = '',
    @产品编码 nvarchar(50) = '',
    @产品名称 nvarchar(50) = '',
    @工序名称 nvarchar(50) = '',
    @要求完工日期1 nvarchar(50) = '',
    @要求完工日期2 nvarchar(50) = '',
    @计划开始1 nvarchar(50) = '',
    @计划开始2 nvarchar(50) = '',
    @计划完成1 nvarchar(50) = '',
    @计划完成2 nvarchar(50) = '',
    @排产状态 nvarchar(50) = '全部',  --全部，已完成、未完成
    @指派对象 nvarchar(50) = '全部',
	@自制件属性 nvarchar(50) = '全部',
	@计划号 nvarchar(50) = '',
	@加急状态 nvarchar(50) = ''
AS
BEGIN
    DECLARE @selectStr NVARCHAR(MAX)
    DECLARE @selectStrWhere NVARCHAR(4000) = ' WHERE [物料类型] = ''pit_Resource'' '
    
    SET @selectStr = N'
        SELECT top 200
			v.计划号,
			加急总数,
			拣配状态,
			自制件属性,
			入库数量,
			case 
                when isnull(任务状态,0)=4 then ''已完成'' 
                when isnull(任务状态,0)=2 then ''已开工'' 
                when isnull(任务状态,0)=0 then ''待执行'' 
                when isnull(任务状态,0)=1 then ''可执行''
                else '''' 
            end as [任务状态],
            case 
                when isnull(加工状态,0)=2 then ''辅助开始''
                when isnull(加工状态,0)=3 then ''辅助结束''
                when isnull(加工状态,0)=4 then ''开始加工''
                when isnull(加工状态,0)=5 then ''暂停''
                when isnull(加工状态,0)=6 then ''报工''
                else '''' 
            end as [加工状态],
            [计划数量订单],
            ISNULL(开工时间, 0) AS 开工时间,
            ISNULL(进度, 0) AS 进度,
            v.[TaskAID],
            [合同号],
            v.[订单编号] AS 订单号,
            [订单行号],
            [订单拆分内码] AS 拆分内码,
            [物料编号] AS 产品编码,
            [物料描述] AS 产品名称,
            TRIM(''.'' FROM TRIM(''0'' FROM CAST([计划数量] AS VARCHAR(30)))) AS 计划数量,
            [计划完成] AS 要求完工日期,
            [工序名称],
            完成数量,
            收料数量,
            CASE 
                WHEN [加急状态] = 1 THEN ''加急'' 
                ELSE '''' 
            END AS 加急状态,
			加急数量,
            性质,
            ISNULL(总工时, 0) AS 总工时,
            [占用情况],
            [排产状态],
            [工序计划数量],
            指派对象编号,
            指派对象,
            TRIM(''.'' FROM TRIM(''0'' FROM CAST([指派数量] AS VARCHAR(30)))) AS 指派数量,
            计划开始时间,
            计划完成时间,
            最晚开始时间,
            [派工状态],
            [外协通知],
            [优先级],
            [未完成说明],
            [派工特殊说明],
            [最后编辑人],
            [最后编辑时间],
            [二次派工],
            CASE 
                WHEN zj_终检.计划号 IS NOT NULL THEN ''是'' 
                ELSE ''否'' 
            END AS 终检,
            -- 新增收检相关字段
            ISNULL(zj_收检.合格数合计, 0) AS 收检合格数,
            ISNULL(zj_收检.不合格数合计, 0) AS 收检不合格数,
            ISNULL(zj_收检.合格数合计, 0) + ISNULL(zj_收检.不合格数合计, 0) AS 收检总数,
			ISNULL(jl.开始时间, 0) AS 开始时间,
            ISNULL(jl.结束时间, 0) AS 结束时间,
			ISNULL(jl.外协结束时间, 0) AS 外协结束时间,
			STUFF((
			SELECT '','' + d2.工序名称
			FROM [dbo].[View_生产订单_MES] d2
			WHERE d2.订单编号 = v.订单编号 order by d2.订单行号
			FOR XML PATH('''')
		), 1, 1, '''') AS 工艺路线
        FROM [dbo].[View_生产订单全部（包括已关闭）] v
        -- 终检判断
        LEFT JOIN (
            SELECT DISTINCT 计划号
            FROM dbo.YL_质量检验_质检记录
            WHERE 质检类型 = ''终检''
        ) zj_终检 ON v.[订单编号] = zj_终检.计划号
        -- 收检数量统计
        LEFT JOIN (
            SELECT 
                TaskAID,
                SUM(ISNULL(合格数, 0)) AS 合格数合计,
                SUM(ISNULL(不合格数, 0)) AS 不合格数合计
            FROM dbo.YL_质量检验_质检记录
            WHERE 质检类型 = ''收检''
            GROUP BY TaskAID
        ) zj_收检 ON v.[TaskAID] = zj_收检.TaskAID
		LEFT JOIN (
            SELECT 
                TaskAID,
                min(ISNULL(开始时间, 0)) AS 开始时间,
				MAX(CASE WHEN 操作类别 = ''报工'' THEN ISNULL(开始时间, 0) ELSE NULL END) AS 外协结束时间,
				MAX(CASE WHEN 操作类别 = ''报工'' THEN ISNULL(结束时间, 0) ELSE NULL END) AS 结束时间
            FROM [dbo].[YL_加工中心_操作记录表]
            GROUP BY TaskAID
        ) jl ON v.[TaskAID] = jl.TaskAID'
    
    -- 添加筛选条件
    IF (@订单号 > 0)
        SET @selectStrWhere = @selectStrWhere + ' AND [订单编号] = ' + CONVERT(VARCHAR(10), @订单号)
    IF (@计划号 > 0)
        SET @selectStrWhere = @selectStrWhere + ' AND v.[计划号] = '''+@计划号+''''
    IF (@合同号 <> '')
        SET @selectStrWhere = @selectStrWhere + ' AND [合同号] LIKE ''%' + @合同号 + '%'''
    
    IF (@产品编码 <> '')
        SET @selectStrWhere = @selectStrWhere + ' AND [物料编号] LIKE ''%' + @产品编码 + '%'''
    
    IF (@产品名称 <> '')
        SET @selectStrWhere = @selectStrWhere + ' AND [物料描述] LIKE ''%' + @产品名称 + '%'''
    
    IF (@工序名称 <> '')
        SET @selectStrWhere = @selectStrWhere + ' AND [工序名称] = ''' + @工序名称 + ''''
    
    IF (@要求完工日期1 <> '')
        SET @selectStrWhere = @selectStrWhere + ' AND [计划完成] >= ''' + @要求完工日期1 + ''''
    
    IF (@要求完工日期2 <> '')
        SET @selectStrWhere = @selectStrWhere + ' AND [计划完成] <= ''' + @要求完工日期2 + ''''
    
    IF (@计划开始1 <> '')
        SET @selectStrWhere = @selectStrWhere + ' AND [计划开始时间] >= ''' + @计划开始1 + ''''
    
    IF (@计划开始2 <> '')
        SET @selectStrWhere = @selectStrWhere + ' AND [计划开始时间] <= ''' + @计划开始2 + ''''
    
    IF (@计划完成1 <> '')
        SET @selectStrWhere = @selectStrWhere + ' AND [计划完成时间] >= ''' + @计划完成1 + ''''
    
    IF (@计划完成2 <> '')
        SET @selectStrWhere = @selectStrWhere + ' AND [计划完成时间] <= ''' + @计划完成2 + ''''
    
    IF (@排产状态 = '未完成')
        SET @selectStrWhere = @selectStrWhere + ' AND ISNULL([排产状态], 0) = 0'
    ELSE IF (@排产状态 = '已完成')
        SET @selectStrWhere = @selectStrWhere + ' AND [排产状态] = 1'
    IF (@自制件属性 = '机加')
        SET @selectStrWhere = @selectStrWhere + ' AND [自制件属性] = ''机加件'''
    ELSE IF (@自制件属性 = '装配')
        SET @selectStrWhere = @selectStrWhere + ' AND [自制件属性] LIKE ''%装配'''
    
    IF (@加急状态 = '加急')
        SET @selectStrWhere = @selectStrWhere + ' AND [加急状态] = 1'
    IF (@指派对象 <> '全部')
        SET @selectStrWhere = @selectStrWhere + ' AND [指派对象] IN (SELECT value FROM STRING_SPLIT(''' + @指派对象 + ''', '',''))'
    
    -- 添加排序
    SET @selectStrWhere = @selectStrWhere + ' ORDER BY [计划完成] ASC, [订单编号] ASC'
    
    -- 合并SQL
    SET @selectStr = @selectStr + @selectStrWhere
    
    -- 打印SQL（调试用）
    PRINT @selectStr
    
    -- 执行查询
    EXEC sp_executesql @selectStr
END
GO
/****** Object:  StoredProcedure [dbo].[生产管理_生产任务汇总]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[生产管理_生产任务汇总]
@订单号 int=0,
@物料类型 nvarchar(50)='自制件',   --自制件、装配件
@合同号 nvarchar(50)='',
@产品编码  nvarchar(50)='',
@产品名称  nvarchar(50)='',
@工序名称  nvarchar(50)='',
@性质  nvarchar(50)='',
@要求完工日期1  nvarchar(50)='',
@要求完工日期2  nvarchar(50)='',
@排产状态  nvarchar(50)='全部',   --全部，已完成、未完成
@工位 nvarchar(500)=''
AS
declare @selectStr nvarchar(4000)
declare @selectStrWhere nvarchar(4000)=' where [物料类型]=''pit_Resource'' and 加工状态 in (2,4) '
if(@物料类型='自制件')   --自制件
	set @selectStr='
		SELECT top 100 isnull([不合格数量],0) as 不合格数量, [收料数量],[合同号],[订单编号] as 订单号,[订单行号],[订单拆分内码] as 拆分内码,[物料编号] as 产品编码,[物料描述] as 产品名称,[计划数量],[计划完成] as 要求完工日期,[工序名称],[加急状态],性质,总工时,[占用情况]
		,[排产状态],[工序计划数量],指派对象编号,指派对象,指派数量,计划开始时间,计划完成时间,最晚开始时间,[派工状态],[外协通知]
		,[优先级],[未完成说明],[派工特殊说明],[最后编辑人],[最后编辑时间],
		isnull([可执行],0) as 可执行,isnull([收料],0) as [收料],isnull([开工],0) as [开工],isnull([首检],0) as [首检],isnull([巡检],0) as [巡检],
		isnull([进度],0) as [进度],isnull([序检],0) as [序检],isnull([测试],0) as [测试],isnull([入库],0) as [入库],TaskAID
		FROM [View_生产订单_MES]'
--else   --装配件
--	set @selectStr='
--		SELECT top 100 isnull([不合格数量],0) as 不合格数量, [收料数量], [合同号],[订单编号] as 订单号,[订单行号],[订单拆分内码] as 拆分内码,[物料编号] as 产品编码,[物料描述] as 产品名称,[计划数量],'''' as 合同交货期,[计划完成] as 预计齐套时间,''齐'' as 是否齐套,'''' as 齐套检测,''是'' as 齐套锁料,[计划开始] as 备料日期,0 as 加急状态,1000 as 总工时,[工序名称],[加急状态],性质,总工时,[占用情况]
--		,[排产状态],[工序计划数量],指派对象编号,指派对象,指派数量,计划开始时间,计划完成时间,最晚开始时间,[派工状态],[外协通知]
--		,[优先级],[未完成说明],[派工特殊说明],[最后编辑人],[最后编辑时间],TaskAID
--		FROM [View_生产订单_MES]'


if(@订单号>0)set @selectStrWhere=@selectStrWhere + ' and [订单编号]='+Convert(VARCHAR(10),@订单号)
if(@合同号<>'')set @selectStrWhere=@selectStrWhere + ' and [合同号] like ''%'+@合同号+'%'''
if(@产品编码<>'')set @selectStrWhere=@selectStrWhere + ' and [物料编号] like ''%'+@产品编码+'%'''
if(@产品名称<>'')set @selectStrWhere=@selectStrWhere + ' and [物料描述] like ''%'+@产品名称+'%'''
if(@工序名称<>'')set @selectStrWhere=@selectStrWhere + ' and [工序名称] = '''+@工序名称+''''
if(@性质<>'')set @selectStrWhere=@selectStrWhere + ' and [性质] = '''+@性质+''''
if(@要求完工日期1 <>'')set @selectStrWhere=@selectStrWhere + ' and [计划完成] >= '''+@要求完工日期1+''''
if(@要求完工日期2 <>'')set @selectStrWhere=@selectStrWhere + ' and [计划完成] <= '''+@要求完工日期2+''''
if(@排产状态='未完成')set @selectStrWhere=@selectStrWhere + ' and isnull([排产状态],0) = 0'
else if(@排产状态='已完成')set @selectStrWhere=@selectStrWhere + ' and [排产状态] = 1'
if(@物料类型='自制件') set @selectStrWhere=@selectStrWhere + ' and [不装配] <> ''否'''
if(@物料类型='装配件') set @selectStrWhere=@selectStrWhere + ' and [不装配] = ''否'''
if(@工位<>'') set @selectStrWhere=@selectStrWhere + ' and [指派对象编号] in ( SELECT value FROM STRING_SPLIT('''+ @工位 +''', '',''))'

set @selectStr=@selectStr+@selectStrWhere
print @selectStr
EXEC sp_executesql @selectStr
GO
/****** Object:  StoredProcedure [dbo].[生产管理_外协报表_查询]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[生产管理_外协报表_查询]
    @订单号 int = 0,
    @合同号 nvarchar(50) = '',
    @产品编码 nvarchar(50) = '',
    @产品名称 nvarchar(50) = '',
    @计划号 nvarchar(50) = '',
    @供应商 nvarchar(100) = '',
    @状态过滤 int = 0,
    @PageCurrent int = 1,
    @PageSize int = 20,
    @PageCount int OUTPUT,
    @ItemCount int OUTPUT
AS
BEGIN
    SET NOCOUNT ON
    
    -- 将合并结果存入临时表
    IF OBJECT_ID('tempdb..#MergedResult') IS NOT NULL DROP TABLE #MergedResult
    
    ;WITH 工单汇总 AS (
        SELECT 
            订单号,
            拆分内码,
            MAX(计划号) AS 计划号,
            MAX(合同号) AS 合同号,
            MAX(产品编码) AS 产品编码,
            MAX(产品名称) AS 产品名称,
            MAX(供应商名称) AS 供应商名称,
            MAX(指派数量) AS 指派数量,
            MAX(含税单价) AS 含税单价,
            MAX(含税行总计) AS 含税行总计,
            MAX(开始时间) AS 开始时间,
            MIN(计划开始时间) AS 计划开始时间,
            MAX(采购预计到货日期) AS 采购预计到货日期,
            MAX(外协结束时间) AS 外协结束时间,
            MAX(收料数量) AS 收料数量,
            MAX(收检合格数) AS 收检合格数,
            MAX(收检不合格数) AS 收检不合格数,
            MAX(CASE WHEN ISNULL(开票数量, 0) > 0 THEN 1 ELSE 0 END) AS 开票数量,
            MAX(发料数量合计) AS 发料数量合计,
            MAX(收料数量_报工) AS 收料数量_报工,
            MAX(CAST(材质 AS NVARCHAR(MAX))) AS 材质,
            MAX(要求完工日期) AS 要求完工日期,
            MAX(工序计划数量) AS 工序计划数量,
            MAX(完成数量) AS 完成数量,
            MAX(收检合格数) AS 上序合格数,
            MAX(CASE WHEN 订单行号 = 1 OR ISNULL(收检合格数, 0) > 0 THEN 1 ELSE 0 END) AS 执行状态,
            STUFF((
                SELECT ',' + d2.工序名称
                FROM View_外协报表视图 d2
                WHERE d2.订单号 = d.订单号 AND d2.拆分内码 = d.拆分内码
                ORDER BY d2.订单行号
                FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)'), 1, 1, '') AS 工序名称列表,
            STUFF((
                SELECT ',' + CAST(d2.TaskAID AS VARCHAR(10))
                FROM View_外协报表视图 d2
                WHERE d2.订单号 = d.订单号 AND d2.拆分内码 = d.拆分内码
                ORDER BY d2.订单行号
                FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)'), 1, 1, '') AS TaskAID列表,
            -- 添加行号用于分页
            ROW_NUMBER() OVER (ORDER BY 订单号) AS RowNum
        FROM View_外协报表视图 d
        WHERE 1=1
          AND (@订单号 = 0 OR d.订单号 = @订单号)
          AND (@计划号 = '' OR d.计划号 = @计划号)
          AND (@合同号 = '' OR d.合同号 LIKE '%' + @合同号 + '%')
          AND (@产品编码 = '' OR d.产品编码 LIKE '%' + @产品编码 + '%')
          AND (@产品名称 = '' OR d.产品名称 LIKE '%' + @产品名称 + '%')
        GROUP BY 订单号, 拆分内码
        HAVING 
            (@供应商 = '' OR MAX(CASE WHEN 供应商名称 LIKE '%' + @供应商 + '%' THEN 1 ELSE 0 END) = 1)
            AND
            (@状态过滤 = 0 OR MAX(CASE WHEN ISNULL(收料数量_报工, 0) < ISNULL(发料数量合计, 0) THEN 1 ELSE 0 END) = 1)
    )
    SELECT 
        计划号,
        合同号,
        订单号,
        产品编码,
        产品名称,
        工序名称列表 AS 工序名称,
        供应商名称,
        指派数量,
        含税单价,
        含税行总计,
        开始时间,
        计划开始时间,
        采购预计到货日期,
        外协结束时间,
        收料数量,
        收检合格数,
        收检不合格数,
        开票数量,
        发料数量合计,
        收料数量_报工,
        材质,
        要求完工日期,
        工序计划数量,
        TaskAID列表 AS TaskAID,
        拆分内码,
        执行状态,
        CASE WHEN 执行状态 = 1 THEN '可执行' ELSE '不可执行' END AS 执行状态文本,
        完成数量,
        上序合格数,
        RowNum
    INTO #MergedResult
    FROM 工单汇总
    
    -- 获取总记录数
    SELECT @ItemCount = COUNT(*) FROM #MergedResult
    
    -- 计算总页数
    IF @ItemCount = 0
        SET @PageCount = 0
    ELSE
        SET @PageCount = CEILING(CAST(@ItemCount AS FLOAT) / @PageSize)
    
    -- 分页返回数据
    SELECT 
        计划号,
        合同号,
        订单号,
        产品编码,
        产品名称,
        工序名称,
        供应商名称,
        指派数量,
        含税单价,
        含税行总计,
        开始时间,
        计划开始时间,
        采购预计到货日期,
        外协结束时间,
        收料数量,
        收检合格数,
        收检不合格数,
        开票数量,
        发料数量合计,
        收料数量_报工,
        材质,
        要求完工日期,
        工序计划数量,
        TaskAID,
        拆分内码,
        执行状态,
        执行状态文本,
        完成数量,
        上序合格数
    FROM #MergedResult
    WHERE RowNum BETWEEN (@PageCurrent - 1) * @PageSize + 1 AND @PageCurrent * @PageSize
    ORDER BY 订单号
    
    -- 清理临时表
    DROP TABLE #MergedResult
END
GO
/****** Object:  StoredProcedure [dbo].[生产管理_外协报表_导出]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[生产管理_外协报表_导出]
    @订单号 int = 0,
    @产品编码 nvarchar(50) = '',
    @产品名称 nvarchar(50) = '',
    @供应商 nvarchar(100) = '',
    @状态过滤 int = 0
AS
BEGIN
    SET NOCOUNT ON
    
    -- 将合并结果存入临时表
    IF OBJECT_ID('tempdb..#MergedResult') IS NOT NULL DROP TABLE #MergedResult
    
    ;WITH 工单汇总 AS (
        SELECT 
            订单号,
            拆分内码,
            MAX(计划号) AS 计划号,
            MAX(合同号) AS 合同号,
            MAX(产品编码) AS 产品编码,
            MAX(产品名称) AS 产品名称,
            MAX(供应商名称) AS 供应商名称,
            MAX(指派数量) AS 指派数量,
            MAX(含税单价) AS 含税单价,
            MAX(含税行总计) AS 含税行总计,
            MAX(开始时间) AS 开始时间,
            MIN(计划开始时间) AS 计划开始时间,
            MAX(采购预计到货日期) AS 采购预计到货日期,
            MAX(外协结束时间) AS 外协结束时间,
            MAX(收料数量) AS 收料数量,
            MAX(收检合格数) AS 收检合格数,
            MAX(收检不合格数) AS 收检不合格数,
            MAX(CASE WHEN ISNULL(开票数量, 0) > 0 THEN 1 ELSE 0 END) AS 开票数量,
            MAX(发料数量合计) AS 发料数量合计,
            MAX(收料数量_报工) AS 收料数量_报工,
            MAX(CAST(材质 AS NVARCHAR(MAX))) AS 材质,
            MAX(要求完工日期) AS 要求完工日期,
            MAX(工序计划数量) AS 工序计划数量,
            MAX(完成数量) AS 完成数量,
            MAX(收检合格数) AS 上序合格数,
            MAX(CASE WHEN 订单行号 = 1 OR ISNULL(收检合格数, 0) > 0 THEN 1 ELSE 0 END) AS 执行状态,
            STUFF((
                SELECT ',' + d2.工序名称
                FROM View_外协报表视图 d2
                WHERE d2.订单号 = d.订单号 AND d2.拆分内码 = d.拆分内码
                ORDER BY d2.订单行号
                FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)'), 1, 1, '') AS 工序名称列表,
            STUFF((
                SELECT ',' + CAST(d2.TaskAID AS VARCHAR(10))
                FROM View_外协报表视图 d2
                WHERE d2.订单号 = d.订单号 AND d2.拆分内码 = d.拆分内码
                ORDER BY d2.订单行号
                FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)'), 1, 1, '') AS TaskAID列表
        FROM View_外协报表视图 d
        WHERE 1=1
          AND (@订单号 = 0 OR d.订单号 = @订单号)
          AND (@产品编码 = '' OR d.产品编码 LIKE '%' + @产品编码 + '%')
          AND (@产品名称 = '' OR d.产品名称 LIKE '%' + @产品名称 + '%')
        GROUP BY 订单号, 拆分内码
        HAVING 
            (@供应商 = '' OR MAX(CASE WHEN 供应商名称 LIKE '%' + @供应商 + '%' THEN 1 ELSE 0 END) = 1)
            AND
            (@状态过滤 = 0 OR MAX(CASE WHEN ISNULL(收料数量_报工, 0) < ISNULL(发料数量合计, 0) THEN 1 ELSE 0 END) = 1)
    )
    SELECT 
        计划号,
        合同号,
        订单号,
        产品编码,
        产品名称,
        工序名称列表 AS 工序名称,
        供应商名称,
        指派数量,
        含税单价,
        含税行总计,
        开始时间,
        计划开始时间,
        采购预计到货日期,
        外协结束时间,
        收料数量,
        收检合格数,
        收检不合格数,
        CASE WHEN 开票数量 > 0 THEN '是' ELSE '否' END AS 开票状态,  -- 导出时直接转换为中文
        发料数量合计,
        收料数量_报工,
        材质,
        要求完工日期,
        工序计划数量,
        TaskAID列表 AS TaskAID,
        拆分内码,
        执行状态,
        CASE WHEN 执行状态 = 1 THEN '可执行' ELSE '不可执行' END AS 执行状态文本,
        完成数量,
        上序合格数
    INTO #MergedResult
    FROM 工单汇总
    
    -- 返回所有数据（不分页）
    SELECT 
        计划号,
        合同号,
        订单号,
        产品编码,
        产品名称,
        工序名称,
        供应商名称,
        指派数量,
        含税单价,
        含税行总计,
        开始时间,
        计划开始时间,
        采购预计到货日期,
        外协结束时间,
        收料数量,
        收检合格数,
        收检不合格数,
        开票状态,  -- 使用转换后的状态
        发料数量合计,
        收料数量_报工,
        材质,
        要求完工日期,
        工序计划数量,
        TaskAID,
        拆分内码,
        执行状态,
        执行状态文本,
        完成数量,
        上序合格数
    FROM #MergedResult
    ORDER BY 订单号
    
    -- 清理临时表
    DROP TABLE #MergedResult
END
GO
/****** Object:  StoredProcedure [dbo].[生产管理_外协管理_查询外协]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- 修改说明：完整实现连续组逻辑，正确应用派工状态和订单状态的双重筛选
-- =============================================
CREATE PROCEDURE [dbo].[生产管理_外协管理_查询外协]
    @订单号 int = 0,
    @产品编码 nvarchar(50) = '',
    @产品名称 nvarchar(50) = '',
    @工序名称 nvarchar(50) = '',
    @派工状态 int = 1,
    @订单状态 int = 0,
    @计划号 nvarchar(50) = '',
	@发料状态 int = 2
AS
BEGIN
    SET NOCOUNT ON;
    
    -- 阶段1：获取基础数据（使用nvarchar避免类型转换错误）
    CREATE TABLE #BaseData (
        RowID int IDENTITY(1,1),
        订单编号 int,
        订单行号 int,
        物料编号 nvarchar(50),
        物料描述 nvarchar(100),
        完成数量 nvarchar(50),
        指派数量 nvarchar(50),
        外协分组 nvarchar(100),
        不合格数量 nvarchar(50),
        收料数量 nvarchar(50),
        合同号 nvarchar(50),
        订单拆分内码 int,
        计划数量 nvarchar(50),
        计划完成 datetime,
        工序名称 nvarchar(50),
        加急状态 nvarchar(50),
        性质 nvarchar(20),
        总工时 nvarchar(50),
        占用情况 nvarchar(20),
        排产状态 nvarchar(20),
        工序计划数量 nvarchar(50),
        指派对象编号 nvarchar(50),
        指派对象 nvarchar(50),
        计划开始时间 datetime,
        计划完成时间 datetime,
        最晚开始时间 datetime,
        派工状态 nvarchar(50),
        外协通知 nvarchar(200),
        计划号 nvarchar(50),
        优先级 nvarchar(50),
        未完成说明 nvarchar(500),
        派工特殊说明 nvarchar(500),
        最后编辑人 nvarchar(50),
        最后编辑时间 datetime,
        外协打印次数 nvarchar(50),
        可执行 nvarchar(50),
        收料 nvarchar(50),
        开工 nvarchar(50),
        首检 nvarchar(50),
        巡检 nvarchar(50),
        进度 nvarchar(50),
        序检 nvarchar(50),
        测试 nvarchar(50),
        入库 nvarchar(50),
        TaskAID int,
        单重 nvarchar(50),
        外协备注 nvarchar(500),
		打印数量 nvarchar(50),
		worker nvarchar(50)
    )
    
    -- 插入基础数据
    INSERT INTO #BaseData (
        订单编号, 订单行号, 物料编号, 物料描述, 完成数量, 指派数量, 外协分组,
        不合格数量, 收料数量, 合同号, 订单拆分内码, 计划数量, 计划完成, 工序名称,
        加急状态, 性质, 总工时, 占用情况, 排产状态, 工序计划数量, 指派对象编号,
        指派对象, 计划开始时间, 计划完成时间, 最晚开始时间, 派工状态, 外协通知,
        计划号, 优先级, 未完成说明, 派工特殊说明, 最后编辑人, 最后编辑时间,
        外协打印次数, 可执行, 收料, 开工, 首检, 巡检, 进度, 序检, 测试, 入库,
        TaskAID, 单重, 外协备注,打印数量,worker
    )
    SELECT 
        v.[订单编号],
        v.[订单行号],
        v.[物料编号],
        v.[物料描述],
        v.[完成数量],
        v.[指派数量],
        v.[外协分组],
        v.[不合格数量],
        v.[收料数量],
        v.[合同号],
        v.[订单拆分内码],
        v.[计划数量],
        v.[计划完成],
        v.[工序名称],
        v.[加急状态],
        v.[性质],
        v.[总工时],
        v.[占用情况],
        v.[排产状态],
        v.[工序计划数量],
        v.[指派对象编号],
        v.[指派对象],
        v.[计划开始时间],
        v.[计划完成时间],
        v.[最晚开始时间],
        v.[派工状态],
        v.[外协通知],
        v.[计划号],
        v.[优先级],
        v.[未完成说明],
        v.[派工特殊说明],
        v.[最后编辑人],
        v.[最后编辑时间],
        v.[外协打印次数],
        v.[可执行],
        v.[收料],
        v.[开工],
        v.[首检],
        v.[巡检],
        v.[进度],
        v.[序检],
        v.[测试],
        v.[入库],
        v.TaskAID,
        v.[单重],
        v.[外协备注],
		v.打印数量,
		v.worker
    FROM [dbo].[View_生产订单_MES] v
    WHERE v.[物料类型] = 'pit_Resource'
        AND v.[指派对象] = '外协'
        AND (@订单号 = 0 OR v.[订单编号] = @订单号)
        AND (@计划号 = '' OR v.[计划号] LIKE '%' + @计划号 + '%')
        AND (@产品编码 = '' OR v.[物料编号] LIKE '%' + @产品编码 + '%')
        AND (@产品名称 = '' OR v.[物料描述] LIKE '%' + @产品名称 + '%')
        AND (@工序名称 = '' OR v.[工序名称] LIKE '%' + @工序名称 + '%')
    
    -- 如果没有数据，直接返回
    IF NOT EXISTS (SELECT 1 FROM #BaseData)
    BEGIN
        SELECT TOP 0 
            NULL as 不合格数量,
            NULL as 收料数量,
            NULL as 合同号,
            NULL as 订单号,
            NULL as 订单行号,
            NULL as 拆分内码,
            NULL as 产品编码,
            NULL as 产品名称,
            NULL as 计划数量,
            NULL as 要求完工日期,
            NULL as 工序名称,
            NULL as 加急状态,
            NULL as 性质,
            NULL as 总工时,
            NULL as 占用情况,
            NULL as 排产状态,
            NULL as 工序计划数量,
            NULL as 指派对象编号,
            NULL as 指派对象,
            NULL as 指派数量,
            NULL as 计划开始时间,
            NULL as 计划完成时间,
            NULL as 最晚开始时间,
            NULL as 派工状态,
            NULL as 外协通知,
            NULL as 计划号,
            NULL as 优先级,
            NULL as 未完成说明,
            NULL as 派工特殊说明,
            NULL as 最后编辑人,
            NULL as 最后编辑时间,
            NULL as 完成数量,
            NULL as 外协打印次数,
            NULL as 可执行,
            NULL as 收料,
            NULL as 开工,
            NULL as 首检,
            NULL as 巡检,
            NULL as 进度,
            NULL as 序检,
            NULL as 测试,
            NULL as 入库,
            NULL as TaskAID,
            NULL as 单重,
            NULL as 外协备注,
            NULL as 外协分组,
            NULL as 上序合格数,
			NULL as 打印数量,
			NULL as worker
        DROP TABLE #BaseData
        RETURN
    END
    
    -- 阶段2：分析连续组并计算组状态
    ;WITH GroupAnalysis AS (
        SELECT 
            bd.*,
            -- 安全转换关键字段用于计算
            CASE 
                WHEN ISNULL(LTRIM(RTRIM(bd.完成数量)), '') = '' THEN 0
                WHEN TRY_CONVERT(decimal(18,2), bd.完成数量) IS NULL THEN 0
                ELSE TRY_CONVERT(decimal(18,2), bd.完成数量)
            END as 完成数量转换,
            CASE 
                WHEN ISNULL(LTRIM(RTRIM(bd.指派数量)), '') = '' THEN 0
                WHEN TRY_CONVERT(decimal(18,2), bd.指派数量) IS NULL THEN 0
                ELSE TRY_CONVERT(decimal(18,2), bd.指派数量)
            END as 指派数量转换,
            CASE 
                WHEN ISNULL(LTRIM(RTRIM(bd.派工状态)), '') = '' THEN 0
                WHEN TRY_CONVERT(int, bd.派工状态) IS NULL THEN 0
                ELSE TRY_CONVERT(int, bd.派工状态)
            END as 派工状态转换,
			CASE 
                WHEN ISNULL(LTRIM(RTRIM(bd.收料数量)), '') = '' THEN 0
                WHEN TRY_CONVERT(int, bd.收料数量) IS NULL THEN 0
                ELSE TRY_CONVERT(int, bd.收料数量)
            END as 发料状态转换,
            -- 标记连续组的开始（新组）
            CASE 
                WHEN NOT EXISTS (
                    SELECT 1 FROM #BaseData prev 
                    WHERE prev.订单编号 = bd.订单编号 
                      AND prev.订单行号 = bd.订单行号 - 1
                      AND ISNULL(prev.外协分组, '') = ISNULL(bd.外协分组, '')
                ) THEN 1
                ELSE 0
            END as 是否组开始
        FROM #BaseData bd
    ),
    ContinuousGroups AS (
        SELECT 
            ga.*,
            -- 为每个连续组分配组ID（使用累加的方式）
            SUM(ga.是否组开始) OVER (
                PARTITION BY ga.订单编号, ga.外协分组 
                ORDER BY ga.订单行号 
                ROWS UNBOUNDED PRECEDING
            ) as 组ID
        FROM GroupAnalysis ga
    ),
    GroupStatus AS (
        SELECT 
            订单编号,
            外协分组,
            组ID,
            -- 组派工状态：组内是否有任何一行已派工
            MAX(CASE WHEN 派工状态转换 = 1 THEN 1 ELSE 0 END) as 组内是否有已派工,
			MAX(CASE WHEN 发料状态转换 = 1 THEN 1 ELSE 0 END) as 组内是否有已发料,
            -- 组完成状态：组内是否有任何一行已完成
            MAX(CASE 
                WHEN 完成数量转换 = 指派数量转换 
                     AND 指派数量转换 > 0 
                THEN 1 
                ELSE 0 
            END) as 组内是否有已完成
        FROM ContinuousGroups
        GROUP BY 订单编号, 外协分组, 组ID
    )
    -- 阶段3：应用双重筛选并返回结果
    SELECT 
        -- 安全转换所有字段
        CASE 
            WHEN ISNULL(LTRIM(RTRIM(bd.不合格数量)), '') = '' THEN 0
            WHEN TRY_CONVERT(decimal(18,2), bd.不合格数量) IS NULL THEN 0
            ELSE TRY_CONVERT(decimal(18,2), bd.不合格数量)
        END as 不合格数量,
        CASE 
            WHEN ISNULL(LTRIM(RTRIM(bd.收料数量)), '') = '' THEN 0
            WHEN TRY_CONVERT(decimal(18,2), bd.收料数量) IS NULL THEN 0
            ELSE TRY_CONVERT(decimal(18,2), bd.收料数量)
        END as 收料数量,
        bd.合同号,
        bd.订单编号 as 订单号,
        bd.订单行号,
        bd.订单拆分内码 as 拆分内码,
        bd.物料编号 as 产品编码,
        bd.物料描述 as 产品名称,
        CASE 
            WHEN ISNULL(LTRIM(RTRIM(bd.计划数量)), '') = '' THEN 0
            WHEN TRY_CONVERT(decimal(18,2), bd.计划数量) IS NULL THEN 0
            ELSE TRY_CONVERT(decimal(18,2), bd.计划数量)
        END as 计划数量,
        bd.计划完成 as 要求完工日期,
        bd.工序名称,
        CASE 
            WHEN ISNULL(LTRIM(RTRIM(bd.加急状态)), '') = '' THEN '0'
            ELSE bd.加急状态
        END as 加急状态,
        bd.性质,
        CASE 
            WHEN ISNULL(LTRIM(RTRIM(bd.总工时)), '') = '' THEN 0
            WHEN TRY_CONVERT(decimal(18,2), bd.总工时) IS NULL THEN 0
            ELSE TRY_CONVERT(decimal(18,2), bd.总工时)
        END as 总工时,
        bd.占用情况,
        bd.排产状态,
        CASE 
            WHEN ISNULL(LTRIM(RTRIM(bd.工序计划数量)), '') = '' THEN 0
            WHEN TRY_CONVERT(decimal(18,2), bd.工序计划数量) IS NULL THEN 0
            ELSE TRY_CONVERT(decimal(18,2), bd.工序计划数量)
        END as 工序计划数量,
        bd.指派对象编号,
        bd.指派对象,
        CASE 
            WHEN ISNULL(LTRIM(RTRIM(bd.指派数量)), '') = '' THEN 0
            WHEN TRY_CONVERT(decimal(18,2), bd.指派数量) IS NULL THEN 0
            ELSE TRY_CONVERT(decimal(18,2), bd.指派数量)
        END as 指派数量,
        bd.计划开始时间,
        bd.计划完成时间,
        bd.最晚开始时间,
        CASE 
            WHEN ISNULL(LTRIM(RTRIM(bd.派工状态)), '') = '' THEN 0
            WHEN TRY_CONVERT(int, bd.派工状态) IS NULL THEN 0
            ELSE TRY_CONVERT(int, bd.派工状态)
        END as 派工状态,
        bd.外协通知,
        bd.计划号,
        CASE 
            WHEN ISNULL(LTRIM(RTRIM(bd.优先级)), '') = '' THEN 0
            WHEN TRY_CONVERT(int, bd.优先级) IS NULL THEN 0
            ELSE TRY_CONVERT(int, bd.优先级)
        END as 优先级,
        bd.未完成说明,
        bd.派工特殊说明,
        bd.最后编辑人,
        bd.最后编辑时间,
        CASE 
            WHEN ISNULL(LTRIM(RTRIM(bd.完成数量)), '') = '' THEN 0
            WHEN TRY_CONVERT(decimal(18,2), bd.完成数量) IS NULL THEN 0
            ELSE TRY_CONVERT(decimal(18,2), bd.完成数量)
        END as 完成数量,
        CASE 
            WHEN ISNULL(LTRIM(RTRIM(bd.外协打印次数)), '') = '' THEN 0
            WHEN TRY_CONVERT(int, bd.外协打印次数) IS NULL THEN 0
            ELSE TRY_CONVERT(int, bd.外协打印次数)
        END as 外协打印次数,
        CASE 
            WHEN ISNULL(LTRIM(RTRIM(bd.可执行)), '') = '' THEN 0
            WHEN TRY_CONVERT(int, bd.可执行) IS NULL THEN 0
            ELSE TRY_CONVERT(int, bd.可执行)
        END as 可执行,
        CASE 
            WHEN ISNULL(LTRIM(RTRIM(bd.收料)), '') = '' THEN 0
            WHEN TRY_CONVERT(int, bd.收料) IS NULL THEN 0
            ELSE TRY_CONVERT(int, bd.收料)
        END as 收料,
        CASE 
            WHEN ISNULL(LTRIM(RTRIM(bd.开工)), '') = '' THEN 0
            WHEN TRY_CONVERT(int, bd.开工) IS NULL THEN 0
            ELSE TRY_CONVERT(int, bd.开工)
        END as 开工,
        CASE 
            WHEN ISNULL(LTRIM(RTRIM(bd.首检)), '') = '' THEN 0
            WHEN TRY_CONVERT(int, bd.首检) IS NULL THEN 0
            ELSE TRY_CONVERT(int, bd.首检)
        END as 首检,
        CASE 
            WHEN ISNULL(LTRIM(RTRIM(bd.巡检)), '') = '' THEN 0
            WHEN TRY_CONVERT(int, bd.巡检) IS NULL THEN 0
            ELSE TRY_CONVERT(int, bd.巡检)
        END as 巡检,
        CASE 
            WHEN ISNULL(LTRIM(RTRIM(bd.进度)), '') = '' THEN 0
            WHEN TRY_CONVERT(decimal(5,2), bd.进度) IS NULL THEN 0
            ELSE TRY_CONVERT(decimal(5,2), bd.进度)
        END as 进度,
        CASE 
            WHEN ISNULL(LTRIM(RTRIM(bd.序检)), '') = '' THEN 0
            WHEN TRY_CONVERT(int, bd.序检) IS NULL THEN 0
            ELSE TRY_CONVERT(int, bd.序检)
        END as 序检,
        CASE 
            WHEN ISNULL(LTRIM(RTRIM(bd.测试)), '') = '' THEN 0
            WHEN TRY_CONVERT(int, bd.测试) IS NULL THEN 0
            ELSE TRY_CONVERT(int, bd.测试)
        END as 测试,
        CASE 
            WHEN ISNULL(LTRIM(RTRIM(bd.入库)), '') = '' THEN 0
            WHEN TRY_CONVERT(int, bd.入库) IS NULL THEN 0
            ELSE TRY_CONVERT(int, bd.入库)
        END as 入库,
        bd.TaskAID,
        CASE 
            WHEN ISNULL(LTRIM(RTRIM(bd.单重)), '') = '' THEN 0
            WHEN TRY_CONVERT(decimal(18,4), bd.单重) IS NULL THEN 0
            ELSE TRY_CONVERT(decimal(18,4), bd.单重)
        END as 单重,
		isnull(bd.打印数量,0) as 打印数量,
		isnull(bd.worker,0) as worker,
        bd.外协备注,
        bd.外协分组,
        -- 计算上序合格数
        ISNULL((
            SELECT TRY_CONVERT(decimal(18,2), SUM(ISNULL(TRY_CONVERT(decimal(18,2), a.合格数), 0)))
            FROM [dbo].[YL_质量检验_质检记录] as a 
            INNER JOIN [dbo].[MES_接口_生产计划_生产任务] as b ON a.TaskAID = b.AID
            WHERE b.订单编号 = bd.订单编号 
              AND b.订单行号 = bd.订单行号 - 1
              AND a.检测类型编号 = 6
        ), 0) as 上序合格数
    FROM ContinuousGroups cg
    INNER JOIN #BaseData bd ON cg.RowID = bd.RowID
    INNER JOIN GroupStatus gs ON cg.订单编号 = gs.订单编号 
        AND ISNULL(cg.外协分组, '') = ISNULL(gs.外协分组, '') 
        AND cg.组ID = gs.组ID
    WHERE 
        -- 应用派工状态筛选（考虑连续组）
        (
            (@派工状态 = 1 AND (cg.派工状态转换 = 1 OR gs.组内是否有已派工 = 1))
            OR
            (@派工状态 = 0 AND cg.派工状态转换 = 0 AND gs.组内是否有已派工 = 0)
            OR
            (@派工状态 NOT IN (0, 1))
        )
        AND
		(
            (@发料状态 = 1 AND (cg.发料状态转换 = 1 OR gs.组内是否有已发料 = 1))
            OR
            (@发料状态 = 0 AND cg.发料状态转换 = 0 AND gs.组内是否有已发料 = 0)
            OR
            (@发料状态 NOT IN (0, 1))
        )
        AND
        -- 应用订单状态筛选（考虑连续组）
        (
            (@订单状态 = 1 AND (
                (cg.完成数量转换 = cg.指派数量转换 AND cg.指派数量转换 > 0)
                OR gs.组内是否有已完成 = 1
            ))
            OR
            (@订单状态 = 0 AND (
                (cg.完成数量转换 <> cg.指派数量转换 OR cg.指派数量转换 = 0)
                AND gs.组内是否有已完成 = 0
            ))
            OR
            (@订单状态 NOT IN (0, 1))
        )
		and bd.排产状态 = 1
    ORDER BY bd.订单编号, bd.订单行号
    
    -- 清理临时表
    DROP TABLE #BaseData
END
GO
/****** Object:  StoredProcedure [dbo].[生产管理_外协管理_查询外协历史记录]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[生产管理_外协管理_查询外协历史记录]
	@maxTaskAID bigint
AS
BEGIN
	select * from [dbo].[YL_加工中心_操作记录表] where 操作类别 in ('收料','报工') and TaskAID = @maxTaskAID  and isnull(操作数值,0) <> 0
END
GO
/****** Object:  StoredProcedure [dbo].[生产管理_外协管理_查询外协全部]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- 修改说明：完整实现连续组逻辑，正确应用派工状态和订单状态的双重筛选
-- =============================================
create PROCEDURE [dbo].[生产管理_外协管理_查询外协全部]
    @订单号 int = 0,
    @产品编码 nvarchar(50) = '',
    @产品名称 nvarchar(50) = '',
    @工序名称 nvarchar(50) = '',
    @派工状态 int = 1,
    @订单状态 int = 0,
    @计划号 nvarchar(50) = '',
	@发料状态 int = 2
AS
BEGIN
    SET NOCOUNT ON;
    
    -- 阶段1：获取基础数据（使用nvarchar避免类型转换错误）
    CREATE TABLE #BaseData (
        RowID int IDENTITY(1,1),
        订单编号 int,
        订单行号 int,
        物料编号 nvarchar(50),
        物料描述 nvarchar(100),
        完成数量 nvarchar(50),
        指派数量 nvarchar(50),
        外协分组 nvarchar(100),
        不合格数量 nvarchar(50),
        收料数量 nvarchar(50),
        合同号 nvarchar(50),
        订单拆分内码 int,
        计划数量 nvarchar(50),
        计划完成 datetime,
        工序名称 nvarchar(50),
        加急状态 nvarchar(50),
        性质 nvarchar(20),
        总工时 nvarchar(50),
        占用情况 nvarchar(20),
        排产状态 nvarchar(20),
        工序计划数量 nvarchar(50),
        指派对象编号 nvarchar(50),
        指派对象 nvarchar(50),
        计划开始时间 datetime,
        计划完成时间 datetime,
        最晚开始时间 datetime,
        派工状态 nvarchar(50),
        外协通知 nvarchar(200),
        计划号 nvarchar(50),
        优先级 nvarchar(50),
        未完成说明 nvarchar(500),
        派工特殊说明 nvarchar(500),
        最后编辑人 nvarchar(50),
        最后编辑时间 datetime,
        外协打印次数 nvarchar(50),
        可执行 nvarchar(50),
        收料 nvarchar(50),
        开工 nvarchar(50),
        首检 nvarchar(50),
        巡检 nvarchar(50),
        进度 nvarchar(50),
        序检 nvarchar(50),
        测试 nvarchar(50),
        入库 nvarchar(50),
        TaskAID int,
        单重 nvarchar(50),
        外协备注 nvarchar(500),
		打印数量 nvarchar(50),
		worker nvarchar(50)
    )
    
    -- 插入基础数据
    INSERT INTO #BaseData (
        订单编号, 订单行号, 物料编号, 物料描述, 完成数量, 指派数量, 外协分组,
        不合格数量, 收料数量, 合同号, 订单拆分内码, 计划数量, 计划完成, 工序名称,
        加急状态, 性质, 总工时, 占用情况, 排产状态, 工序计划数量, 指派对象编号,
        指派对象, 计划开始时间, 计划完成时间, 最晚开始时间, 派工状态, 外协通知,
        计划号, 优先级, 未完成说明, 派工特殊说明, 最后编辑人, 最后编辑时间,
        外协打印次数, 可执行, 收料, 开工, 首检, 巡检, 进度, 序检, 测试, 入库,
        TaskAID, 单重, 外协备注,打印数量,worker
    )
    SELECT 
        v.[订单编号],
        v.[订单行号],
        v.[物料编号],
        v.[物料描述],
        v.[完成数量],
        v.[指派数量],
        v.[外协分组],
        v.[不合格数量],
        v.[收料数量],
        v.[合同号],
        v.[订单拆分内码],
        v.[计划数量],
        v.[计划完成],
        v.[工序名称],
        v.[加急状态],
        v.[性质],
        v.[总工时],
        v.[占用情况],
        v.[排产状态],
        v.[工序计划数量],
        v.[指派对象编号],
        v.[指派对象],
        v.[计划开始时间],
        v.[计划完成时间],
        v.[最晚开始时间],
        v.[派工状态],
        v.[外协通知],
        v.[计划号],
        v.[优先级],
        v.[未完成说明],
        v.[派工特殊说明],
        v.[最后编辑人],
        v.[最后编辑时间],
        v.[外协打印次数],
        v.[可执行],
        v.[收料],
        v.[开工],
        v.[首检],
        v.[巡检],
        v.[进度],
        v.[序检],
        v.[测试],
        v.[入库],
        v.TaskAID,
        v.[单重],
        v.[外协备注],
		v.打印数量,
		v.worker
    FROM [dbo].[View_生产订单全部（包括已关闭）] v
    WHERE v.[物料类型] = 'pit_Resource'
        AND v.[指派对象] = '外协'
        AND (@订单号 = 0 OR v.[订单编号] = @订单号)
        AND (@计划号 = '' OR v.[计划号] LIKE '%' + @计划号 + '%')
        AND (@产品编码 = '' OR v.[物料编号] LIKE '%' + @产品编码 + '%')
        AND (@产品名称 = '' OR v.[物料描述] LIKE '%' + @产品名称 + '%')
        AND (@工序名称 = '' OR v.[工序名称] LIKE '%' + @工序名称 + '%')
    
    -- 如果没有数据，直接返回
    IF NOT EXISTS (SELECT 1 FROM #BaseData)
    BEGIN
        SELECT TOP 0 
            NULL as 不合格数量,
            NULL as 收料数量,
            NULL as 合同号,
            NULL as 订单号,
            NULL as 订单行号,
            NULL as 拆分内码,
            NULL as 产品编码,
            NULL as 产品名称,
            NULL as 计划数量,
            NULL as 要求完工日期,
            NULL as 工序名称,
            NULL as 加急状态,
            NULL as 性质,
            NULL as 总工时,
            NULL as 占用情况,
            NULL as 排产状态,
            NULL as 工序计划数量,
            NULL as 指派对象编号,
            NULL as 指派对象,
            NULL as 指派数量,
            NULL as 计划开始时间,
            NULL as 计划完成时间,
            NULL as 最晚开始时间,
            NULL as 派工状态,
            NULL as 外协通知,
            NULL as 计划号,
            NULL as 优先级,
            NULL as 未完成说明,
            NULL as 派工特殊说明,
            NULL as 最后编辑人,
            NULL as 最后编辑时间,
            NULL as 完成数量,
            NULL as 外协打印次数,
            NULL as 可执行,
            NULL as 收料,
            NULL as 开工,
            NULL as 首检,
            NULL as 巡检,
            NULL as 进度,
            NULL as 序检,
            NULL as 测试,
            NULL as 入库,
            NULL as TaskAID,
            NULL as 单重,
            NULL as 外协备注,
            NULL as 外协分组,
            NULL as 上序合格数,
			NULL as 打印数量,
			NULL as worker
        DROP TABLE #BaseData
        RETURN
    END
    
    -- 阶段2：分析连续组并计算组状态
    ;WITH GroupAnalysis AS (
        SELECT 
            bd.*,
            -- 安全转换关键字段用于计算
            CASE 
                WHEN ISNULL(LTRIM(RTRIM(bd.完成数量)), '') = '' THEN 0
                WHEN TRY_CONVERT(decimal(18,2), bd.完成数量) IS NULL THEN 0
                ELSE TRY_CONVERT(decimal(18,2), bd.完成数量)
            END as 完成数量转换,
            CASE 
                WHEN ISNULL(LTRIM(RTRIM(bd.指派数量)), '') = '' THEN 0
                WHEN TRY_CONVERT(decimal(18,2), bd.指派数量) IS NULL THEN 0
                ELSE TRY_CONVERT(decimal(18,2), bd.指派数量)
            END as 指派数量转换,
            CASE 
                WHEN ISNULL(LTRIM(RTRIM(bd.派工状态)), '') = '' THEN 0
                WHEN TRY_CONVERT(int, bd.派工状态) IS NULL THEN 0
                ELSE TRY_CONVERT(int, bd.派工状态)
            END as 派工状态转换,
			CASE 
                WHEN ISNULL(LTRIM(RTRIM(bd.收料数量)), '') = '' THEN 0
                WHEN TRY_CONVERT(int, bd.收料数量) IS NULL THEN 0
                ELSE TRY_CONVERT(int, bd.收料数量)
            END as 发料状态转换,
            -- 标记连续组的开始（新组）
            CASE 
                WHEN NOT EXISTS (
                    SELECT 1 FROM #BaseData prev 
                    WHERE prev.订单编号 = bd.订单编号 
                      AND prev.订单行号 = bd.订单行号 - 1
                      AND ISNULL(prev.外协分组, '') = ISNULL(bd.外协分组, '')
                ) THEN 1
                ELSE 0
            END as 是否组开始
        FROM #BaseData bd
    ),
    ContinuousGroups AS (
        SELECT 
            ga.*,
            -- 为每个连续组分配组ID（使用累加的方式）
            SUM(ga.是否组开始) OVER (
                PARTITION BY ga.订单编号, ga.外协分组 
                ORDER BY ga.订单行号 
                ROWS UNBOUNDED PRECEDING
            ) as 组ID
        FROM GroupAnalysis ga
    ),
    GroupStatus AS (
        SELECT 
            订单编号,
            外协分组,
            组ID,
            -- 组派工状态：组内是否有任何一行已派工
            MAX(CASE WHEN 派工状态转换 = 1 THEN 1 ELSE 0 END) as 组内是否有已派工,
			MAX(CASE WHEN 发料状态转换 = 1 THEN 1 ELSE 0 END) as 组内是否有已发料,
            -- 组完成状态：组内是否有任何一行已完成
            MAX(CASE 
                WHEN 完成数量转换 = 指派数量转换 
                     AND 指派数量转换 > 0 
                THEN 1 
                ELSE 0 
            END) as 组内是否有已完成
        FROM ContinuousGroups
        GROUP BY 订单编号, 外协分组, 组ID
    )
    -- 阶段3：应用双重筛选并返回结果
    SELECT 
        -- 安全转换所有字段
        CASE 
            WHEN ISNULL(LTRIM(RTRIM(bd.不合格数量)), '') = '' THEN 0
            WHEN TRY_CONVERT(decimal(18,2), bd.不合格数量) IS NULL THEN 0
            ELSE TRY_CONVERT(decimal(18,2), bd.不合格数量)
        END as 不合格数量,
        CASE 
            WHEN ISNULL(LTRIM(RTRIM(bd.收料数量)), '') = '' THEN 0
            WHEN TRY_CONVERT(decimal(18,2), bd.收料数量) IS NULL THEN 0
            ELSE TRY_CONVERT(decimal(18,2), bd.收料数量)
        END as 收料数量,
        bd.合同号,
        bd.订单编号 as 订单号,
        bd.订单行号,
        bd.订单拆分内码 as 拆分内码,
        bd.物料编号 as 产品编码,
        bd.物料描述 as 产品名称,
        CASE 
            WHEN ISNULL(LTRIM(RTRIM(bd.计划数量)), '') = '' THEN 0
            WHEN TRY_CONVERT(decimal(18,2), bd.计划数量) IS NULL THEN 0
            ELSE TRY_CONVERT(decimal(18,2), bd.计划数量)
        END as 计划数量,
        bd.计划完成 as 要求完工日期,
        bd.工序名称,
        CASE 
            WHEN ISNULL(LTRIM(RTRIM(bd.加急状态)), '') = '' THEN '0'
            ELSE bd.加急状态
        END as 加急状态,
        bd.性质,
        CASE 
            WHEN ISNULL(LTRIM(RTRIM(bd.总工时)), '') = '' THEN 0
            WHEN TRY_CONVERT(decimal(18,2), bd.总工时) IS NULL THEN 0
            ELSE TRY_CONVERT(decimal(18,2), bd.总工时)
        END as 总工时,
        bd.占用情况,
        bd.排产状态,
        CASE 
            WHEN ISNULL(LTRIM(RTRIM(bd.工序计划数量)), '') = '' THEN 0
            WHEN TRY_CONVERT(decimal(18,2), bd.工序计划数量) IS NULL THEN 0
            ELSE TRY_CONVERT(decimal(18,2), bd.工序计划数量)
        END as 工序计划数量,
        bd.指派对象编号,
        bd.指派对象,
        CASE 
            WHEN ISNULL(LTRIM(RTRIM(bd.指派数量)), '') = '' THEN 0
            WHEN TRY_CONVERT(decimal(18,2), bd.指派数量) IS NULL THEN 0
            ELSE TRY_CONVERT(decimal(18,2), bd.指派数量)
        END as 指派数量,
        bd.计划开始时间,
        bd.计划完成时间,
        bd.最晚开始时间,
        CASE 
            WHEN ISNULL(LTRIM(RTRIM(bd.派工状态)), '') = '' THEN 0
            WHEN TRY_CONVERT(int, bd.派工状态) IS NULL THEN 0
            ELSE TRY_CONVERT(int, bd.派工状态)
        END as 派工状态,
        bd.外协通知,
        bd.计划号,
        CASE 
            WHEN ISNULL(LTRIM(RTRIM(bd.优先级)), '') = '' THEN 0
            WHEN TRY_CONVERT(int, bd.优先级) IS NULL THEN 0
            ELSE TRY_CONVERT(int, bd.优先级)
        END as 优先级,
        bd.未完成说明,
        bd.派工特殊说明,
        bd.最后编辑人,
        bd.最后编辑时间,
        CASE 
            WHEN ISNULL(LTRIM(RTRIM(bd.完成数量)), '') = '' THEN 0
            WHEN TRY_CONVERT(decimal(18,2), bd.完成数量) IS NULL THEN 0
            ELSE TRY_CONVERT(decimal(18,2), bd.完成数量)
        END as 完成数量,
        CASE 
            WHEN ISNULL(LTRIM(RTRIM(bd.外协打印次数)), '') = '' THEN 0
            WHEN TRY_CONVERT(int, bd.外协打印次数) IS NULL THEN 0
            ELSE TRY_CONVERT(int, bd.外协打印次数)
        END as 外协打印次数,
        CASE 
            WHEN ISNULL(LTRIM(RTRIM(bd.可执行)), '') = '' THEN 0
            WHEN TRY_CONVERT(int, bd.可执行) IS NULL THEN 0
            ELSE TRY_CONVERT(int, bd.可执行)
        END as 可执行,
        CASE 
            WHEN ISNULL(LTRIM(RTRIM(bd.收料)), '') = '' THEN 0
            WHEN TRY_CONVERT(int, bd.收料) IS NULL THEN 0
            ELSE TRY_CONVERT(int, bd.收料)
        END as 收料,
        CASE 
            WHEN ISNULL(LTRIM(RTRIM(bd.开工)), '') = '' THEN 0
            WHEN TRY_CONVERT(int, bd.开工) IS NULL THEN 0
            ELSE TRY_CONVERT(int, bd.开工)
        END as 开工,
        CASE 
            WHEN ISNULL(LTRIM(RTRIM(bd.首检)), '') = '' THEN 0
            WHEN TRY_CONVERT(int, bd.首检) IS NULL THEN 0
            ELSE TRY_CONVERT(int, bd.首检)
        END as 首检,
        CASE 
            WHEN ISNULL(LTRIM(RTRIM(bd.巡检)), '') = '' THEN 0
            WHEN TRY_CONVERT(int, bd.巡检) IS NULL THEN 0
            ELSE TRY_CONVERT(int, bd.巡检)
        END as 巡检,
        CASE 
            WHEN ISNULL(LTRIM(RTRIM(bd.进度)), '') = '' THEN 0
            WHEN TRY_CONVERT(decimal(5,2), bd.进度) IS NULL THEN 0
            ELSE TRY_CONVERT(decimal(5,2), bd.进度)
        END as 进度,
        CASE 
            WHEN ISNULL(LTRIM(RTRIM(bd.序检)), '') = '' THEN 0
            WHEN TRY_CONVERT(int, bd.序检) IS NULL THEN 0
            ELSE TRY_CONVERT(int, bd.序检)
        END as 序检,
        CASE 
            WHEN ISNULL(LTRIM(RTRIM(bd.测试)), '') = '' THEN 0
            WHEN TRY_CONVERT(int, bd.测试) IS NULL THEN 0
            ELSE TRY_CONVERT(int, bd.测试)
        END as 测试,
        CASE 
            WHEN ISNULL(LTRIM(RTRIM(bd.入库)), '') = '' THEN 0
            WHEN TRY_CONVERT(int, bd.入库) IS NULL THEN 0
            ELSE TRY_CONVERT(int, bd.入库)
        END as 入库,
        bd.TaskAID,
        CASE 
            WHEN ISNULL(LTRIM(RTRIM(bd.单重)), '') = '' THEN 0
            WHEN TRY_CONVERT(decimal(18,4), bd.单重) IS NULL THEN 0
            ELSE TRY_CONVERT(decimal(18,4), bd.单重)
        END as 单重,
		isnull(bd.打印数量,0) as 打印数量,
		isnull(bd.worker,0) as worker,
        bd.外协备注,
        bd.外协分组,
        -- 计算上序合格数
        ISNULL((
            SELECT TRY_CONVERT(decimal(18,2), SUM(ISNULL(TRY_CONVERT(decimal(18,2), a.合格数), 0)))
            FROM [dbo].[YL_质量检验_质检记录] as a 
            INNER JOIN [dbo].[MES_接口_生产计划_生产任务] as b ON a.TaskAID = b.AID
            WHERE b.订单编号 = bd.订单编号 
              AND b.订单行号 = bd.订单行号 - 1
              AND a.检测类型编号 = 6
        ), 0) as 上序合格数
    FROM ContinuousGroups cg
    INNER JOIN #BaseData bd ON cg.RowID = bd.RowID
    INNER JOIN GroupStatus gs ON cg.订单编号 = gs.订单编号 
        AND ISNULL(cg.外协分组, '') = ISNULL(gs.外协分组, '') 
        AND cg.组ID = gs.组ID
    WHERE 
        -- 应用派工状态筛选（考虑连续组）
        (
            (@派工状态 = 1 AND (cg.派工状态转换 = 1 OR gs.组内是否有已派工 = 1))
            OR
            (@派工状态 = 0 AND cg.派工状态转换 = 0 AND gs.组内是否有已派工 = 0)
            OR
            (@派工状态 NOT IN (0, 1))
        )
        AND
		(
            (@发料状态 = 1 AND (cg.发料状态转换 = 1 OR gs.组内是否有已发料 = 1))
            OR
            (@发料状态 = 0 AND cg.发料状态转换 = 0 AND gs.组内是否有已发料 = 0)
            OR
            (@发料状态 NOT IN (0, 1))
        )
        AND
        -- 应用订单状态筛选（考虑连续组）
        (
            (@订单状态 = 1 AND (
                (cg.完成数量转换 = cg.指派数量转换 AND cg.指派数量转换 > 0)
                OR gs.组内是否有已完成 = 1
            ))
            OR
            (@订单状态 = 0 AND (
                (cg.完成数量转换 <> cg.指派数量转换 OR cg.指派数量转换 = 0)
                AND gs.组内是否有已完成 = 0
            ))
            OR
            (@订单状态 NOT IN (0, 1))
        )
		and bd.排产状态 = 1
    ORDER BY bd.订单编号, bd.订单行号
    
    -- 清理临时表
    DROP TABLE #BaseData
END
GO
/****** Object:  StoredProcedure [dbo].[生产管理_外协管理_查询质检记录]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
create PROCEDURE [dbo].[生产管理_外协管理_查询质检记录]
	@maxTaskAID bigint
AS
BEGIN
	select * from [dbo].[YL_质量检验_质检记录] where TaskAID = @maxTaskAID 
END
GO
/****** Object:  StoredProcedure [dbo].[生产管理_外协管理_更新备注]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[生产管理_外协管理_更新备注]
    @订单编号列表 NVARCHAR(MAX),
	@外协备注  NVARCHAR(MAX) = '',
	@单重  NVARCHAR(50) = '',
	@打印数量 NVARCHAR(50) = ''
AS
BEGIN
    SET NOCOUNT ON;
    
    BEGIN TRY
        BEGIN TRANSACTION;
        
        -- 创建临时表存储订单编号
        CREATE TABLE #TempOrders (订单编号 NVARCHAR(100));
        
        -- 解析逗号分隔的订单编号列表
        INSERT INTO #TempOrders (订单编号)
        SELECT value 
        FROM STRING_SPLIT(@订单编号列表, ',')
        WHERE LTRIM(RTRIM(value)) <> '';
        
        -- 更新打印次数
        UPDATE [dbo].[MES_接口_生产计划_生产任务]
        SET 外协备注 = @外协备注,单重 = @单重, 打印数量 = @打印数量
        WHERE AID IN (SELECT 订单编号 FROM #TempOrders);
        
        -- 检查更新了多少行
        DECLARE @UpdateCount INT = @@ROWCOUNT;
        
        -- 返回成功信息
        SELECT 
            '成功' AS 状态,
            @UpdateCount AS 更新记录数,
            '成功更新' + CAST(@UpdateCount AS NVARCHAR(10)) + '条记录的信息' AS 消息;
        
        DROP TABLE #TempOrders;
        
        COMMIT TRANSACTION;
    END TRY
    BEGIN CATCH
        IF @@TRANCOUNT > 0
            ROLLBACK TRANSACTION;
        
        -- 返回错误信息
        SELECT 
            '错误' AS 状态,
            0 AS 更新记录数,
            ERROR_MESSAGE() AS 消息;
        
        IF OBJECT_ID('tempdb..#TempOrders') IS NOT NULL
            DROP TABLE #TempOrders;
    END CATCH
END


GO
/****** Object:  StoredProcedure [dbo].[生产管理_外协管理_更新打印次数]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

create PROCEDURE [dbo].[生产管理_外协管理_更新打印次数]
    @订单编号列表 NVARCHAR(MAX)
AS
BEGIN
    SET NOCOUNT ON;
    
    BEGIN TRY
        BEGIN TRANSACTION;
        
        -- 创建临时表存储订单编号
        CREATE TABLE #TempOrders (订单编号 NVARCHAR(100));
        
        -- 解析逗号分隔的订单编号列表
        INSERT INTO #TempOrders (订单编号)
        SELECT value 
        FROM STRING_SPLIT(@订单编号列表, ',')
        WHERE LTRIM(RTRIM(value)) <> '';
        
        -- 更新打印次数
        UPDATE [dbo].[MES_接口_生产计划_生产任务]
        SET 外协打印次数 = ISNULL(外协打印次数, 0) + 1
        WHERE AID IN (SELECT 订单编号 FROM #TempOrders);
        
        -- 检查更新了多少行
        DECLARE @UpdateCount INT = @@ROWCOUNT;
        
        -- 返回成功信息
        SELECT 
            '成功' AS 状态,
            @UpdateCount AS 更新记录数,
            '成功更新' + CAST(@UpdateCount AS NVARCHAR(10)) + '条记录的打印次数' AS 消息;
        
        DROP TABLE #TempOrders;
        
        COMMIT TRANSACTION;
    END TRY
    BEGIN CATCH
        IF @@TRANCOUNT > 0
            ROLLBACK TRANSACTION;
        
        -- 返回错误信息
        SELECT 
            '错误' AS 状态,
            0 AS 更新记录数,
            ERROR_MESSAGE() AS 消息;
        
        IF OBJECT_ID('tempdb..#TempOrders') IS NOT NULL
            DROP TABLE #TempOrders;
    END CATCH
END


GO
/****** Object:  StoredProcedure [dbo].[生产管理_外协管理_外协发料保存]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[生产管理_外协管理_外协发料保存]
	@TaskAID bigint,
	@recievCount int,
	@optor nvarchar(50),
	@单重 nvarchar(50) = '',
	@备注 nvarchar(50) = ''

AS
declare @操作时间 datetime=getdate()
declare @任务状态 int
BEGIN
	--更新收料数量、收料状态、可执行状态
	select @任务状态 = isnull(任务状态,0) from MES_接口_生产计划_生产任务 where AID=@TaskAID
	if(@任务状态 <= 1 )
	begin 
		Update MES_接口_生产计划_生产任务 
		set 任务状态=case when isnull(收料数量,0)+@recievCount>0 then 1 else 0 end,   --当收料数量>0时，变为可执行
		收料=case when isnull(收料数量,0)+@recievCount>0 then 1 else 0 end,
		收料数量=isnull(收料数量,0)+@recievCount,
		修改时间=@操作时间
		where AID=@TaskAID
	end
	if(@任务状态 > 1 )
	begin 
		Update MES_接口_生产计划_生产任务 
		set 收料=case when isnull(收料数量,0)+@recievCount>0 then 1 else 0 end,
		收料数量=isnull(收料数量,0)+@recievCount,
		修改时间=@操作时间
		where AID=@TaskAID
	end
	--生成操作记录
	declare @词条名称 nvarchar(50)='收料'
	declare @数据类别 nvarchar(50)='生产操作'
	EXEC	[dbo].[MES_ProductCenter_OptRecord_Save]
		@dicItemName = @词条名称,
		@dataType = @数据类别,
		@TaskAID = @TaskAID,
		@optCount = @recievCount,
		@optDescription = @备注,
		@optor = @optor,
		@optTime = @操作时间



END
GO
/****** Object:  StoredProcedure [dbo].[生产管理_外协管理_外协发料查询]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[生产管理_外协管理_外协发料查询]
	@maxTaskAID bigint,
	@minTaskAID bigint
AS
BEGIN
    -- 先获取@minTaskAID对应的订单编号和行号
    DECLARE @上序订单编号 INT
    DECLARE @上序订单行号 INT
    
    SELECT @上序订单编号 = [订单编号],
           @上序订单行号 = [订单行号]
    FROM [dbo].[View_生产订单_MES]
    WHERE [TaskAID] = @minTaskAID

    SELECT [订单编号]
          ,[合同号]
          ,[物料编号]
          ,[物料描述]
          ,[占用情况]
          ,[加急状态]
          ,[排产状态]
          ,[订单行号]
          ,[阶段标识]
          ,[工序名称]
          ,[顺序编号]
          ,[总工时]
          ,[不装配]
          ,[指派对象编号]
          ,[指派对象]
          ,ISNULL([指派数量],0) as [指派数量]
          ,[计划开始时间]
          ,[计划完成时间]
          ,[最晚开始时间]
          ,[派工状态]
          ,[派工时间]
          ,[任务状态]
          ,[修改时间]
          ,[外协通知]
          ,[优先级]
          ,[未完成说明]
          ,[派工特殊说明]
          ,[最后编辑人]
          ,[最后编辑时间]
          ,[订单拆分内码]
          ,[计划数量]
          ,ISNULL([可执行],0) as [可执行]
          ,[收料]
          ,ISNULL([收料数量],0) as [收料数量]
          ,[开工]
          ,[首检]
          ,[巡检]
          ,ISNULL([完成数量],0) as [完成数量]
          ,[进度]
          ,[序检]
          ,[测试]
          ,[入库]
          ,ISNULL([加工状态],0) as [加工状态]
          ,[TaskAID]
          ,ISNULL((
              SELECT SUM(ISNULL(qc.合格数, 0)) 
              FROM [dbo].[YL_质量检验_质检记录] qc
              INNER JOIN [dbo].[View_生产订单_MES] vt ON qc.TaskAID = vt.TaskAID
              WHERE vt.[订单编号] = vo.[订单编号]
                AND vt.[订单行号] = @上序订单行号 - 1
                AND qc.检测类型编号 = '6'
          ), 0) as [上序合格数]
          -- 添加@minTaskAID对应的上序合格数作为独立字段
          ,ISNULL((
              SELECT SUM(ISNULL(qc.合格数, 0))
              FROM [dbo].[YL_质量检验_质检记录] qc
              WHERE qc.TaskAID = @minTaskAID
                AND qc.检测类型编号 = '6'
          ), 0) as [指定任务合格数]
          ,@上序订单编号 as [上序订单编号]
          ,@上序订单行号 as [上序订单行号]
    FROM [dbo].[View_生产订单_MES] vo
    WHERE [TaskAID] = @maxTaskAID
END
GO
/****** Object:  StoredProcedure [dbo].[生产管理_外协管理_外协历史查询]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[生产管理_外协管理_外协历史查询]
	@TaskAID bigint
AS
BEGIN
--declare @订单编号 int=-1
--declare @订单行号 int=-1
--select @订单编号=[订单编号],@订单行号 = 订单行号 FROM [View_生产订单_MES] where TaskAID=@TaskAID
SELECT 
      操作描述,
	  最后编辑时间,
	  操作数值,
	  TaskAID
  FROM [dbo].[YL_加工中心_操作记录表]
  WHERE [TaskAID]=@TaskAID and 操作类别 = '收料'
END
GO
/****** Object:  StoredProcedure [dbo].[生产管理_外协管理_外协收料保存]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[生产管理_外协管理_外协收料保存]
	@TaskAID bigint,
	@recievCount int,
	@optor nvarchar(50)
AS
declare @操作时间 datetime=getdate()
declare @任务状态 int
BEGIN


	Update MES_接口_生产计划_生产任务 
	set 完成数量=isnull(完成数量,0)+@recievCount,
	最后编辑时间=@操作时间,
	最后编辑人 = @optor
	where AID=@TaskAID

	--生成操作记录
	declare @词条名称 nvarchar(50)='报工'
	declare @数据类别 nvarchar(50)='生产操作'
	EXEC	[dbo].[MES_ProductCenter_OptRecord_Save]
		@dicItemName = @词条名称,
		@dataType = @数据类别,
		@TaskAID = @TaskAID,
		@optCount = @recievCount,
		--@optDescription = N'Description',
		@optor = @optor,
		@optTime = @操作时间


END
GO
/****** Object:  StoredProcedure [dbo].[生产管理_装配中心_缺料查询]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[生产管理_装配中心_缺料查询]
	@ItemCode nvarchar(500),
	@订单号 int
AS
BEGIN
	select * from SAP.SBO_YL.dbo.UBT_OPKL_MissQty where  DocEntry = @订单号
END
GO
/****** Object:  StoredProcedure [dbo].[生产管理_装配状态_获取进行中任务]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[生产管理_装配状态_获取进行中任务]
    @操作人 nvarchar(50) = ''
AS
BEGIN
    SET NOCOUNT ON;
    
    BEGIN TRY
        -- 简化版本，只查询必要的字段
        SELECT 
            t.AID AS 操作记录ID,
            t.TaskAID,
            t.操作人 AS UserName,
            t.开始时间 AS StartTime,
            t.操作类别,
            t.操作类别编号,
            t.工序名称,
            t.工位名称,
            t.订单编号,
            t.物料编号,
            t.物料描述,
            t.阶段标识,
            -- 从生产任务表获取信息
            mes.订单编号 AS 订单号,
            mes.物料编码 AS 零件编码,
            mes.物料名称 AS 零件名称,
            mes.工序名称 AS 任务工序名称,
            mes.指派对象,
            mes.任务状态,
            mes.指派数量 AS 分配数,
            mes.完成数量,
            mes.计划开始时间 AS 计划开始,
            mes.计划完成时间 AS 计划完成,
            mes.顺序编号 AS 阶段标识编号,
			mes.[加急总数],
		    mes.[入库数量],
		    mes.[计划号],
		    mes.[合同号],
		    case 
                when isnull(mes.齐套,0)=1 then '是' 
                when isnull(mes.齐套,0)=0 then '否'
			end as [齐套],
			case 
                when isnull(mes.发料状态,0)=1 then '发料齐套' 
                when isnull(mes.发料状态,0)=2 then '发料缺件'
			end as [发料状态],
			case 
                when isnull(mes.拣配状态,0)=1 then '已拣配' 
                when isnull(mes.拣配状态,0)=0 then '未拣配'
			end as [拣配状态],
			ISNULL(zj_收检.合格数合计, 0) AS 收检合格数,
			ISNULL(zj_收检.不合格数合计, 0) AS 收检不合格数
            
        FROM [dbo].[YL_加工中心_操作记录表] t
		LEFT JOIN [dbo].[View_生产订单_MES] mes ON mes.TaskAID = t.TaskAID
		LEFT JOIN (
            SELECT 
                TaskAID,
                SUM(ISNULL(合格数, 0)) AS 合格数合计,
                SUM(ISNULL(不合格数, 0)) AS 不合格数合计
            FROM dbo.YL_质量检验_质检记录
            WHERE 质检类型 = '收检'
            GROUP BY TaskAID
        ) zj_收检 ON mes.TaskAID = zj_收检.TaskAID
        WHERE 
             t.操作类别 = '开始加工'
            AND t.结束时间 IS NULL
			and t.工位名称 like '%装配%'
			and t.操作数值 is not null
			-- 增加操作人过滤条件
			AND (@操作人 = '' OR t.操作人 = @操作人)
        ORDER BY t.操作人,t.开始时间 DESC;
        
        -- 返回状态信息
        SELECT '1' AS result, '查询成功' AS message;
        
    END TRY
    BEGIN CATCH
        DECLARE @ErrorMessage NVARCHAR(4000);
        SELECT @ErrorMessage = ERROR_MESSAGE();
        
        SELECT '0' AS result, '查询失败: ' + @ErrorMessage AS message;
        
        RAISERROR (@ErrorMessage, 16, 1);
    END CATCH
END
GO
/****** Object:  StoredProcedure [dbo].[生产任务综合看板_按期齐套率]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[生产任务综合看板_按期齐套率]
AS
BEGIN
    SET NOCOUNT ON;

	SELECT 
		COUNT(*) AS [总任务数],
		SUM(CASE WHEN ISNULL(齐套, 0) = 1 THEN 1 ELSE 0 END) AS [齐套任务数],
		SUM(CASE WHEN ISNULL(齐套, 0) = 0 THEN 1 ELSE 0 END) AS [未齐套任务数],
		CAST(SUM(CASE WHEN ISNULL(齐套, 0) = 1 THEN 1 ELSE 0 END) * 100.0 / COUNT(*) AS DECIMAL(5,2)) AS [齐套率],
    
		-- 按发料状态细分
		SUM(CASE WHEN ISNULL(发料状态, 0) = 1 THEN 1 ELSE 0 END) AS [发料齐套任务数],
		SUM(CASE WHEN ISNULL(发料状态, 0) = 2 THEN 1 ELSE 0 END) AS [发料缺件任务数],
		SUM(CASE WHEN ISNULL(发料状态, 0) = 0 THEN 1 ELSE 0 END) AS [未发料任务数]
	FROM [View_生产订单_MES] 
	WHERE 计划开始时间 < GETDATE() 
	  AND 同步时间 >= DATEADD(MONTH, -1, GETDATE())
END
GO
/****** Object:  StoredProcedure [dbo].[生产任务综合看板_加急任务查询]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

create PROCEDURE [dbo].[生产任务综合看板_加急任务查询]
AS
BEGIN
    SET NOCOUNT ON;

	SELECT [AID]
      ,[订单编号]
      ,[合同号]
      ,[订单类型]
      ,[订单状态]
      ,[物料编号]
      ,[物料描述]
      ,[计划数量]
      ,[计量单位]
      ,[下达日期]
      ,[计划开始]
      ,[计划完成]
      ,[自制件属性]
      ,COUNT(*) OVER() AS [加急订单总数]  -- 新增汇总列
FROM [YL_MESDB].[dbo].[MES_接口_生产计划] 
WHERE 加急数量 > 0

END
GO
/****** Object:  StoredProcedure [dbo].[生产任务综合看板_未按期齐套任务]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[生产任务综合看板_未按期齐套任务]
AS
BEGIN
    SET NOCOUNT ON;

	SELECT *
	FROM [View_生产订单_MES] 
	WHERE 计划开始时间 < GETDATE() 
	  AND 同步时间 >= DATEADD(MONTH, -1, GETDATE())
	  and isnull(齐套,0) = 0
END
GO
/****** Object:  StoredProcedure [dbo].[生产任务综合看板_未及时开工查询]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[生产任务综合看板_未及时开工查询]
AS
BEGIN
    DECLARE @selStr nvarchar(max) = 
    'SELECT COUNT(*) AS [未及时开工总数]
     FROM (
         SELECT TaskAID
         FROM [View_生产订单_MES] AS main
         WHERE 排产状态 = 1 
            AND [指派对象] <> ''外协'' 
            AND [指派对象] NOT LIKE ''%装配%'' 
            AND [指派对象] <> ''期初物料''  
            AND (计划开始时间 < 开工时间 OR 开工时间 IS NULL) 
            AND ISNULL(加工状态,0) = 0
            AND ISNULL(任务状态, 0) IN (0,1,2)
     ) AS FilteredTasks'

    -- 调试用（上线前可注释掉）
    PRINT @selStr

    EXEC sp_executesql @selStr
END
GO
/****** Object:  StoredProcedure [dbo].[生产任务综合看板_未及时开工查询_Count]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[生产任务综合看板_未及时开工查询_Count]
AS
BEGIN
    DECLARE @selStr nvarchar(max) = 
    'SELECT COUNT(*) AS [未及时开工总数]
     FROM (
         SELECT TaskAID
         FROM [View_生产订单_MES] AS main
         WHERE 排产状态 = 1 
            AND [指派对象] <> ''外协'' 
            AND [指派对象] NOT LIKE ''%装配%'' 
            AND [指派对象] <> ''期初物料''  
            AND (计划开始时间 < 开工时间 OR 开工时间 IS NULL) 
            AND ISNULL(加工状态,0) = 0
            AND ISNULL(任务状态, 0) IN (0,1,2)
     ) AS FilteredTasks'

    -- 调试用（上线前可注释掉）
    PRINT @selStr

    EXEC sp_executesql @selStr
END
GO
/****** Object:  StoredProcedure [dbo].[生产任务综合看板_未排产无工艺查询]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

create PROCEDURE [dbo].[生产任务综合看板_未排产无工艺查询]
AS
BEGIN
    SET NOCOUNT ON;

	SELECT 
    (SELECT COUNT(*) 
     FROM [YL_MESDB].[dbo].[MES_接口_生产计划_生产任务] 
     WHERE ISNULL(排产状态, 0) = 0) AS [未排产任务数],
    
    (SELECT COUNT(*) 
     FROM [YL_MESDB].[dbo].[MES_接口_生产计划] 
     WHERE ISNULL(生产工艺, 0) = 0) AS [无生产工艺计划数]
END
GO
/****** Object:  StoredProcedure [dbo].[刷新外协报表合并表]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- 创建存储过程
CREATE PROCEDURE [dbo].[刷新外协报表合并表]
AS
BEGIN
    SET NOCOUNT ON
    
    -- 如果表不存在，创建表
    IF OBJECT_ID('外协报表合并表', 'U') IS NULL
    BEGIN
        CREATE TABLE 外协报表合并表 (
            计划号 nvarchar(50),
            合同号 nvarchar(50),
            订单号 int,
            产品编码 nvarchar(50),
            产品名称 nvarchar(50),
            工序名称 nvarchar(max),
            供应商名称 nvarchar(200),
            指派数量 decimal(18,2),
            含税单价 decimal(18,2),
            含税行总计 decimal(18,2),
            开始时间 datetime,
            计划开始时间 datetime,
            采购预计到货日期 datetime,
            外协结束时间 datetime,
            收料数量 int,
            收检合格数 decimal(18,2),
            收检不合格数 decimal(18,2),
            开票数量 int,
            发料数量合计 int,
            收料数量_报工 int,
            材质 nvarchar(max),
            要求完工日期 datetime,
            工序计划数量 decimal(18,2),
            TaskAID nvarchar(max),
            拆分内码 int,
            执行状态 int,
            执行状态文本 nvarchar(10),
            完成数量 int,
            上序合格数 decimal(18,2),
            PRIMARY KEY (订单号, 拆分内码)
        )
    END
    
    -- 清空表数据
    TRUNCATE TABLE 外协报表合并表
    
    -- 插入合并后的数据
    ;WITH 工单组 AS (
        SELECT 
            订单号,
            拆分内码,
            MAX(计划号) AS 计划号,
            MAX(合同号) AS 合同号,
            MAX(产品编码) AS 产品编码,
            MAX(产品名称) AS 产品名称,
            MAX(供应商名称) AS 供应商名称,
            MAX(指派数量) AS 指派数量,
            MAX(含税单价) AS 含税单价,
            MAX(含税行总计) AS 含税行总计,
            MAX(开始时间) AS 开始时间,
            MIN(计划开始时间) AS 计划开始时间,
            MAX(采购预计到货日期) AS 采购预计到货日期,
            MAX(外协结束时间) AS 外协结束时间,
            MAX(收料数量) AS 收料数量,
            MAX(收检合格数) AS 收检合格数,
            MAX(收检不合格数) AS 收检不合格数,
            MAX(CASE WHEN ISNULL(开票数量, 0) > 0 THEN 1 ELSE 0 END) AS 开票数量,
            MAX(发料数量合计) AS 发料数量合计,
            MAX(收料数量_报工) AS 收料数量_报工,
            MAX(CAST(材质 AS NVARCHAR(MAX))) AS 材质,
            MAX(要求完工日期) AS 要求完工日期,
            MAX(工序计划数量) AS 工序计划数量,
            MAX(完成数量) AS 完成数量,
            MAX(收检合格数) AS 上序合格数,
            MAX(CASE WHEN 订单行号 = 1 OR ISNULL(收检合格数, 0) > 0 THEN 1 ELSE 0 END) AS 执行状态,
            -- 工序名称拼接
            STUFF((SELECT ',' + v2.工序名称 
                   FROM View_外协报表视图 v2 
                   WHERE v2.订单号 = v.订单号 AND v2.拆分内码 = v.拆分内码 
                   ORDER BY v2.订单行号 
                   FOR XML PATH('')), 1, 1, '') AS 工序名称列表,
            -- TaskAID拼接
            STUFF((SELECT ',' + CAST(v2.TaskAID AS VARCHAR(10))
                   FROM View_外协报表视图 v2 
                   WHERE v2.订单号 = v.订单号 AND v2.拆分内码 = v.拆分内码 
                   ORDER BY v2.订单行号 
                   FOR XML PATH('')), 1, 1, '') AS TaskAID列表
        FROM View_外协报表视图 v
        GROUP BY 订单号, 拆分内码
    )
    INSERT INTO 外协报表合并表
    SELECT 
        计划号,
        合同号,
        订单号,
        产品编码,
        产品名称,
        工序名称列表,
        供应商名称,
        指派数量,
        含税单价,
        含税行总计,
        开始时间,
        计划开始时间,
        采购预计到货日期,
        外协结束时间,
        收料数量,
        收检合格数,
        收检不合格数,
        开票数量,
        发料数量合计,
        收料数量_报工,
        材质,
        要求完工日期,
        工序计划数量,
        TaskAID列表,
        拆分内码,
        执行状态,
        CASE WHEN 执行状态 = 1 THEN '可执行' ELSE '不可执行' END,
        完成数量,
        上序合格数
    FROM 工单组
END
GO
/****** Object:  StoredProcedure [dbo].[系统管理_报工操作记录_查询]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[系统管理_报工操作记录_查询]
    @订单编号 NVARCHAR(100) = NULL,
    @操作人 NVARCHAR(100) = NULL
AS
BEGIN
    SET NOCOUNT ON;
    
    SELECT top 100
      *
    FROM [dbo].[YL_加工中心_操作记录表]
    WHERE 1 = 1
        AND (@订单编号 IS NULL OR 订单编号 = @订单编号)
        AND (@操作人 IS NULL OR 操作人 = @操作人)
    ORDER BY AID DESC
END
GO
/****** Object:  StoredProcedure [dbo].[系统管理_工位管理_工位绑定人员保存]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[系统管理_工位管理_工位绑定人员保存]
    @工位号 NVARCHAR(50),
    @人员编号列表 NVARCHAR(MAX)
AS
BEGIN
    SET NOCOUNT ON;
    
    BEGIN TRY
        BEGIN TRANSACTION;
        
        -- 1. 先将该工位所有现有绑定标记为解绑
        UPDATE 工位人员绑定表 
        SET 绑定状态 = 0 
        WHERE 工位号 = @工位号 AND 绑定状态 = 1;
        
        -- 2. 如果人员编号列表不为空，则插入新的绑定关系
        IF @人员编号列表 IS NOT NULL AND LEN(LTRIM(RTRIM(@人员编号列表))) > 0
        BEGIN
            -- 创建临时表存储人员编号
            CREATE TABLE #临时人员表 (
                人员编号 INT
            );
            
            -- 将逗号分隔的字符串拆分成人员编号
            INSERT INTO #临时人员表 (人员编号)
            SELECT CAST(value AS INT)
            FROM STRING_SPLIT(@人员编号列表, ',') 
            WHERE LTRIM(RTRIM(value)) != '';
            
            -- 插入新的绑定关系
            INSERT INTO 工位人员绑定表 (工位号, 人员编号, 绑定时间, 绑定人, 绑定状态)
            SELECT @工位号, 人员编号, GETDATE(), '系统', 1
            FROM #临时人员表;
            
            -- 删除临时表
            DROP TABLE #临时人员表;
        END
        
        COMMIT TRANSACTION;
        
        -- 返回成功结果
        SELECT 
            1 AS 执行结果, 
            '人员绑定成功' AS 提示信息,
            @工位号 AS 工位号;
            
    END TRY
    BEGIN CATCH
        ROLLBACK TRANSACTION;
        
        -- 返回失败结果
        SELECT 
            0 AS 执行结果, 
            '人员绑定失败: ' + ERROR_MESSAGE() AS 提示信息,
            @工位号 AS 工位号;
    END CATCH
END
GO
/****** Object:  StoredProcedure [dbo].[系统管理_工位管理_工位绑定人员查询]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[系统管理_工位管理_工位绑定人员查询]
    @工位号 NVARCHAR(50)
AS
BEGIN
    SET NOCOUNT ON;
    
    SELECT 
        p.Personnel_Number AS 人员编号,
        p.Personnel_Name AS 人员姓名,
        p.account AS 账号,
        p.Roles_Function AS 角色,
        wb.绑定时间
    FROM 工位人员绑定表 wb
    INNER JOIN [dbo].[登录基础数据_管理人员权限视图] p ON wb.人员编号 = p.Personnel_Number
    WHERE wb.工位号 = @工位号 
    AND wb.绑定状态 = 1
    AND p.Quit = 0  -- 只显示未离职人员
    ORDER BY p.Personnel_Name;
END
GO
/****** Object:  StoredProcedure [dbo].[系统管理_工位管理_工位信息删除]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO






CREATE    PROCEDURE [dbo].[系统管理_工位管理_工位信息删除]
@工位号 nvarchar(50) 
AS

SET NOCOUNT ON;

begin

--declare @是否分配菜单 int 
--declare @是否分配人员 int 

--select @是否分配菜单 = COUNT(*) from [dbo].[登录基础数据_二级菜单] where  账号代码 = @工位号
--select @是否分配人员 = COUNT(*) from [dbo].[登录基础数据_人员权限角色] where  Roles_number = @工位号

--if @是否分配菜单 > 0
--	begin
--		select 0 as result
--		return
--	end

--if @是否分配人员 > 0
--	begin
--		select 2 as result
--		return
--	end

 delete from [dbo].[MES_资源主数据] where [VisCode] = @工位号
 select 1 as result

end
GO
/****** Object:  StoredProcedure [dbo].[系统管理_工位管理_工位信息修改]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE     PROCEDURE [dbo].[系统管理_工位管理_工位信息修改]
@工位名称 nvarchar(50),
@工位号 nvarchar(50)
AS


DECLARE @同名工位是否存在 int = 0

SELECT @同名工位是否存在 = count(*) FROM [MES_资源主数据] WHERE  [Name] = @工位名称

if(@同名工位是否存在 = 0)
begin
UPDATE [dbo].[MES_资源主数据]
SET 
[Name]=@工位名称
WHERE [VisCode] = @工位号

select 1 as result
end
else
begin
select 2 as result
end
GO
/****** Object:  StoredProcedure [dbo].[系统管理_工位管理_工位信息增加]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE    PROCEDURE [dbo].[系统管理_工位管理_工位信息增加]

@工位名称 nvarchar(50),
@工位号 nvarchar(50)
AS



DECLARE @同名工位是否存在 int = 0
SELECT @同名工位是否存在 = count(*) FROM [MES_资源主数据] WHERE  [Name] = @工位名称

if(@同名工位是否存在 = 0)
begin
INSERT INTO [dbo].[MES_资源主数据]( [Name],[VisCode],[Type],[Active],[IssueMethod],[Allocation],[SyncTime],[ResourceGroup],[ForeignName],[UnitOfMeasure])
VALUES(@工位名称,@工位号,'rtMachine','tYES','rimManual','raOnStartDate',GETDATE(),1,'','')
select 1 as result
end
else
begin
select 2 as result
end



GO
/****** Object:  StoredProcedure [dbo].[系统管理_人员管理_所有有效人员查询]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[系统管理_人员管理_所有有效人员查询]
AS
BEGIN
    SET NOCOUNT ON;
    
    SELECT 
        Personnel_Number AS 人员编号,
        Personnel_Name AS 人员姓名,
        account AS 账号,
        Roles_Function AS 角色,
        部门名称
    FROM [dbo].[登录基础数据_管理人员权限视图]
    WHERE Quit = 0  -- 只查询未离职的人员
    ORDER BY Personnel_Name;
END
GO
/****** Object:  StoredProcedure [dbo].[销售管理_销售订单状态]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE  PROCEDURE [dbo].[销售管理_销售订单状态]
    @订单号 int = 0,
    @物料类型 nvarchar(50) = '',   --自制件、装配件
    @合同号 nvarchar(50) = '',
    @产品编码 nvarchar(50) = '',
    @产品名称 nvarchar(50) = '',
    @工序名称 nvarchar(50) = '',
    @要求完工日期1 nvarchar(50) = '',
    @要求完工日期2 nvarchar(50) = '',
    @计划开始1 nvarchar(50) = '',
    @计划开始2 nvarchar(50) = '',
    @计划完成1 nvarchar(50) = '',
    @计划完成2 nvarchar(50) = '',
    @排产状态 nvarchar(50) = '全部',  --全部，已完成、未完成
    @指派对象 nvarchar(50) = '全部',
	@计划号 nvarchar(50) = '',
	@发货状态 nvarchar(50) = '全部',  --全部，已发货、未发货
	@入库状态 nvarchar(50) = '全部'
AS
BEGIN
    DECLARE @selectStr NVARCHAR(MAX)
    DECLARE @selectStrWhere NVARCHAR(4000) = ' WHERE [物料类型] = ''pit_Resource'' and 自制件属性 LIKE ''%装配%''  '
    
    SET @selectStr = N'
        SELECT top 200
			v.计划号,
			拣配状态,
			入库数量,
			要求发货日期,
			isnull(发货状态,0) as [发货状态],
			case 
                when isnull(发料状态,0)=1 then ''发料齐套'' 
                when isnull(发料状态,0)=2 then ''发料缺件''
				when isnull(发料状态,0)=0 then ''未发料''
			end as [发料状态],
			case 
                when isnull(齐套,0)=1 then ''是'' 
				when isnull(齐套,0)=0 then ''否''
			end as [齐套],
			自制件属性,
			case 
                when isnull(任务状态,0)=4 then ''已完成'' 
                when isnull(任务状态,0)=2 then ''已开工'' 
                when isnull(任务状态,0)=0 then ''待执行'' 
                when isnull(任务状态,0)=1 then ''可执行''
                else '''' 
            end as [任务状态],
            case 
                when isnull(加工状态,0)=2 then ''辅助开始''
                when isnull(加工状态,0)=3 then ''辅助结束''
                when isnull(加工状态,0)=4 then ''开始加工''
                when isnull(加工状态,0)=5 then ''暂停''
                when isnull(加工状态,0)=6 then ''报工''
                else '''' 
            end as [加工状态],
            [计划数量订单],
            ISNULL(开工时间, 0) AS 开工时间,
            ISNULL(进度, 0) AS 进度,
            v.[TaskAID],
            [合同号],
            v.[订单编号] AS 订单号,
            [订单行号],
            [订单拆分内码] AS 拆分内码,
            [物料编号] AS 产品编码,
            [物料描述] AS 产品名称,
            TRIM(''.'' FROM TRIM(''0'' FROM CAST([计划数量] AS VARCHAR(30)))) AS 计划数量,
            [计划完成] AS 要求完工日期,
            [工序名称],
            完成数量,
            收料数量,
            CASE 
                WHEN [加急状态] = 1 THEN ''加急'' 
                ELSE '''' 
            END AS 加急状态,
			加急数量,
            性质,
            ISNULL(总工时, 0) AS 总工时,
            [占用情况],
            [排产状态],
            [工序计划数量],
            指派对象编号,
            指派对象,
            TRIM(''.'' FROM TRIM(''0'' FROM CAST([指派数量] AS VARCHAR(30)))) AS 指派数量,
            计划开始时间,
            计划完成时间,
            最晚开始时间,
            [派工状态],
            [外协通知],
            [优先级],
            [未完成说明],
            [派工特殊说明],
            [最后编辑人],
            [最后编辑时间],
            [二次派工],
            CASE 
                WHEN zj_终检.计划号 IS NOT NULL THEN ''是'' 
                ELSE ''否'' 
            END AS 终检,
            -- 新增收检相关字段
            ISNULL(zj_收检.合格数合计, 0) AS 收检合格数,
            ISNULL(zj_收检.不合格数合计, 0) AS 收检不合格数,
            ISNULL(zj_收检.合格数合计, 0) + ISNULL(zj_收检.不合格数合计, 0) AS 收检总数,
			生产工艺,
			ISNULL(zj_终检数量.终检合格数合计, 0) AS 终检合格数,
            ISNULL(zj_终检数量.终检不合格数合计, 0) AS 终检不合格数
        FROM [View_生产订单_MES] v
        -- 终检判断
        LEFT JOIN (
            SELECT DISTINCT 计划号
            FROM dbo.YL_质量检验_质检记录
            WHERE 质检类型 = ''终检''
        ) zj_终检 ON v.[订单编号] = zj_终检.计划号
        -- 收检数量统计
        LEFT JOIN (
            SELECT 
                TaskAID,
                SUM(ISNULL(合格数, 0)) AS 合格数合计,
                SUM(ISNULL(不合格数, 0)) AS 不合格数合计
            FROM dbo.YL_质量检验_质检记录
            WHERE 质检类型 = ''收检''
            GROUP BY TaskAID
        ) zj_收检 ON v.[TaskAID] = zj_收检.TaskAID 
		
        LEFT JOIN (
            SELECT 
                TaskAID,
                SUM(ISNULL(合格数, 0)) AS 终检合格数合计,
                SUM(ISNULL(不合格数, 0)) AS 终检不合格数合计
            FROM dbo.YL_质量检验_质检记录
            WHERE 质检类型 = ''终检''
            GROUP BY TaskAID
        ) zj_终检数量 ON v.[TaskAID] = zj_终检数量.TaskAID'

    
    -- 添加筛选条件
    IF (@订单号 > 0)
        SET @selectStrWhere = @selectStrWhere + ' AND [订单编号] = ' + CONVERT(VARCHAR(10), @订单号)
    IF (@计划号 > 0)
        SET @selectStrWhere = @selectStrWhere + ' AND v.[计划号] = '''+@计划号+''''
    IF (@合同号 <> '')
        SET @selectStrWhere = @selectStrWhere + ' AND [合同号] LIKE ''%' + @合同号 + '%'''
    
    IF (@产品编码 <> '')
        SET @selectStrWhere = @selectStrWhere + ' AND [物料编号] LIKE ''%' + @产品编码 + '%'''
    
    IF (@产品名称 <> '')
        SET @selectStrWhere = @selectStrWhere + ' AND [物料描述] LIKE ''%' + @产品名称 + '%'''
    
    IF (@工序名称 <> '')
        SET @selectStrWhere = @selectStrWhere + ' AND [工序名称] = ''' + @工序名称 + ''''
    
    IF (@要求完工日期1 <> '')
        SET @selectStrWhere = @selectStrWhere + ' AND [计划完成] >= ''' + @要求完工日期1 + ''''
    
    IF (@要求完工日期2 <> '')
        SET @selectStrWhere = @selectStrWhere + ' AND [计划完成] <= ''' + @要求完工日期2 + ''''
    
    IF (@计划开始1 <> '')
        SET @selectStrWhere = @selectStrWhere + ' AND [计划开始时间] >= ''' + @计划开始1 + ''''
    
    IF (@计划开始2 <> '')
        SET @selectStrWhere = @selectStrWhere + ' AND [计划开始时间] <= ''' + @计划开始2 + ''''
    
    IF (@计划完成1 <> '')
        SET @selectStrWhere = @selectStrWhere + ' AND [计划完成时间] >= ''' + @计划完成1 + ''''
    
    IF (@计划完成2 <> '')
        SET @selectStrWhere = @selectStrWhere + ' AND [计划完成时间] <= ''' + @计划完成2 + ''''
    
    IF (@排产状态 = '未完成')
        SET @selectStrWhere = @selectStrWhere + ' AND ISNULL([排产状态], 0) = 0'
    ELSE IF (@排产状态 = '已完成')
        SET @selectStrWhere = @selectStrWhere + ' AND [排产状态] = 1'
	IF (@发货状态 = '未发货')
        SET @selectStrWhere = @selectStrWhere + ' AND ISNULL([发货状态], 0) = 0'
    ELSE IF (@发货状态 = '已发货')
        SET @selectStrWhere = @selectStrWhere + ' AND [发货状态] = 1'

    IF (@指派对象 <> '全部')
        SET @selectStrWhere = @selectStrWhere + ' AND [指派对象] IN (SELECT value FROM STRING_SPLIT(''' + @指派对象 + ''', '',''))'
    IF (@入库状态 = '未完成')
    SET @selectStrWhere = @selectStrWhere + ' AND ISNULL([终检合格数合计], 0) + ISNULL([终检不合格数合计], 0) + ISNULL(不合格数合计,0) <= 计划数量订单  
        AND (ISNULL([终检合格数合计], 0) <= 0 OR ISNULL([终检合格数合计],0) > ISNULL([入库数量], 0))'
    ELSE IF (@入库状态 = '已完成')
        SET @selectStrWhere = @selectStrWhere + ' AND ISNULL([终检合格数合计], 0) + ISNULL([终检不合格数合计], 0) + ISNULL(不合格数合计,0) = 计划数量订单  AND ISNULL([入库数量], 0) =  ISNULL([终检合格数合计], 0)'
    -- 添加排序
    SET @selectStrWhere = @selectStrWhere + ' ORDER BY [合同号] DESC, [订单编号] DESC '
    
    -- 合并SQL
    SET @selectStr = @selectStr + @selectStrWhere
    
    -- 打印SQL（调试用）
    PRINT @selectStr
    
    -- 执行查询
    EXEC sp_executesql @selectStr
END
GO
/****** Object:  StoredProcedure [dbo].[异常工时_新增操作记录]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- 工时校验_新增操作记录（修改版）
CREATE PROCEDURE [dbo].[异常工时_新增操作记录]
    @操作类别 nvarchar(50),
    @订单编号 nvarchar(50),
    @物料编号 nvarchar(50),
    @物料描述 nvarchar(50),
    @工序名称 nvarchar(50),
    @操作人 nvarchar(50),
    @开始时间 datetime,
    @结束时间 datetime,
    @操作内容 nvarchar(500) = NULL,
    @操作描述 nvarchar(2000) = NULL,
	@TaskAID nvarchar(2000) = NULL

AS
BEGIN
    SET NOCOUNT ON;
    
    BEGIN TRY
        DECLARE @工时 int;
		DECLARE @工位名称 nvarchar(500);
		select @工位名称 = 指派对象 from [dbo].[View_生产订单_MES] where TaskAID = @TaskAID
        
        -- 计算工时（秒）
        SET @工时 = DATEDIFF(SECOND, @开始时间, @结束时间);
        
        -- 插入操作记录表
        INSERT INTO [dbo].[YL_加工中心_操作记录表] (
            操作类别编号, 操作类别, 阶段标识, 工序名称, 工位编号, 
            操作人, 合同号, 订单编号, 物料编号, 物料描述, 操作数值, 操作内容,
            操作描述, 开始时间, 结束时间, 总时长, 报工日期, 已报工, 不装配,
            最后编辑人, 最后编辑时间,TaskAID,工位名称
        ) VALUES (
		    @操作类别,
            CASE @操作类别 
                WHEN '8' THEN '加班'
				WHEN '9' THEN '异常'
            END,
            0,  -- 阶段标识
            @工序名称,
            '',  -- 工位编号
            @操作人,
            '',  -- 合同号
            @订单编号,
            @物料编号,
            @物料描述,
            0,  -- 操作数值（固定为0，已去掉该字段）
            @操作内容,
            @操作描述,
            @开始时间,
            @结束时间,
            @工时,
            CONVERT(date, GETDATE()),
            1,  -- 已报工
            '否',  -- 不装配
            @操作人,
            GETDATE(),
			@TaskAID,
			@工位名称
        );
        
        SELECT '成功' as 结果, '新增操作记录成功' as 消息, SCOPE_IDENTITY() as 新记录ID;
        
    END TRY
    BEGIN CATCH
        SELECT '错误' as 结果, ERROR_MESSAGE() as 消息, NULL as 新记录ID;
    END CATCH
END
GO
/****** Object:  StoredProcedure [dbo].[异常提醒_及时开工_查询]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[异常提醒_及时开工_查询]
	@TaskAID int =-1,
    @订单号 int = -1,
    @零件编号 nvarchar(50) = '',
    @计划开工_Start nvarchar(50) = '',
    @计划开工_End nvarchar(50) = '',
    @生产状态 int = -1,	-- -1: 未指定；0: 待执行；1: 可执行；2: 已开工；4: 已完工
    @工位名称 nvarchar(500) = '',
	@用户ID nvarchar(50) = '',
	@计划号 nvarchar(50) = '',
	@销售订单 nvarchar(50) = ''
AS
BEGIN
    DECLARE @whereStr nvarchar(max) = ' WHERE 排产状态 = 1 '
    DECLARE @selStr nvarchar(max) = 
    'SELECT TaskAID,
            [订单编号] as 订单号,
			合同号,
			加急总数,
			派工特殊说明,
            [订单拆分内码],
            [订单行号],
            [开工时间],
            [物料编号] as 零件编码,
            [物料描述] as 零件名称,
            case when isnull([加急状态],0)=1 then ''加急'' else ''否'' end as [加急],
            [优先级] as [优先],
            [指派对象编号],
            [指派对象],
            [工序名称],
			[二次派工],
			[计划号],
            isnull([指派数量],0) as 分配数,
            [计划开始时间] as 计划开始,
            [计划完成时间] as 计划完成,
            [最晚开始时间] as 最晚开始,
            isnull([收料数量],0) as 收料,
            isnull([完成数量],0) as 完成数量,
			case 
                when isnull(齐套,0)=1 then ''是'' 
                when isnull(齐套,0)=0 then ''否''
			end as [齐套],
			case 
                when isnull(发料状态,0)=1 then ''发料齐套'' 
                when isnull(发料状态,0)=2 then ''发料缺件''
			end as [发料状态],
			case 
                when isnull(拣配状态,0)=1 then ''已拣配'' 
                when isnull(拣配状态,0)=0 then ''未拣配''
			end as [拣配状态],
            case 
                when isnull(任务状态,0)=4 then ''已完成'' 
                when isnull(任务状态,0)=2 then ''已开工'' 
                when isnull(任务状态,0)=0 then ''待执行'' 
                when isnull(任务状态,0)=1 then ''可执行''
                else '''' 
            end as [任务状态],
            case 
                when isnull(加工状态,0)=2 then ''辅助开始''
                when isnull(加工状态,0)=3 then ''辅助结束''
                when isnull(加工状态,0)=4 then ''开始加工''
                when isnull(加工状态,0)=5 then ''暂停''
                when isnull(加工状态,0)=6 then ''报工''
                else '''' 
            end as [加工状态],
            isnull(加工状态,0) as 加工状态编号,
            case when isnull([首检],-1)=1 then ''OK'' when isnull([首检],-1)=0 then ''NG'' else '''' end as [首检],
            case when isnull([序检],-1)=1 then ''OK'' when isnull([序检],-1)=0 then ''NG'' else '''' end as [序检],
            -- 新增：下序名称
            (SELECT TOP 1 [工序名称] 
             FROM [View_生产订单_MES] AS next_task 
             WHERE next_task.[订单编号] = main.[订单编号] 
               AND next_task.[订单行号] = main.[订单行号] + 1
               AND next_task.[排产状态] = 1
             ORDER BY next_task.[订单行号]) AS 下序名称,
			 (
                   SELECT ISNULL(SUM(ISNULL(a.合格数, 0)), 0)
                   FROM [dbo].[YL_质量检验_质检记录] as a 
                   INNER JOIN [dbo].[MES_接口_生产计划_生产任务] as b ON a.TaskAID = b.AID
                   WHERE b.订单编号 = main.[订单编号] 
                     AND b.订单行号 = main.[订单行号] - 1
					 AND a.检测类型编号 = 6
               ) as 上序合格数,
			   (
				SELECT STRING_AGG(a.Personnel_Name, '','') 
				FROM [dbo].[登录基础数据_人员信息] AS a 
				WHERE EXISTS (
					SELECT 1 
					FROM [dbo].[MES_接口_生产计划_生产任务] AS b 
					WHERE b.订单编号 = main.订单编号 
					  AND b.订单行号 = main.订单行号
					  AND EXISTS (
						  SELECT 1 
						  FROM STRING_SPLIT(b.二次派工, '','') AS ids
						  WHERE LTRIM(RTRIM(ids.value)) = CAST(a.Personnel_Number AS VARCHAR(50))
					  )
				)
			) as 二次派工名称
     FROM [View_生产订单_MES] AS main'

    -- 基础过滤：排除外协
    SET @whereStr = @whereStr + ' AND [指派对象] <> ''外协'' AND [指派对象] NOT LIKE ''%装配%'' AND [指派对象] <> ''期初物料''  and  (计划开始时间 < 开工时间 or 开工时间 is null) and isnull(加工状态,0) = 0 '

    -- 订单号
    IF (@订单号 > 0)
        SET @whereStr = @whereStr + ' AND [订单编号] = ' + CONVERT(VARCHAR(10), @订单号)
	IF (@计划号 > 0)
        SET @whereStr = @whereStr + ' AND [计划号] = '''+@计划号+'''' 
	IF (@销售订单<> '')
        SET @whereStr = @whereStr + ' AND [合同号] LIKE ''%' + @销售订单 + '%''' 
	IF (@TaskAID > 0)
        SET @whereStr = @whereStr + ' AND [TaskAID] = ' + CONVERT(VARCHAR(10), @TaskAID)
    -- 零件编号（模糊）
    IF (@零件编号 <> '')
        SET @whereStr = @whereStr + ' AND [物料编号] LIKE ''%' + @零件编号 + '%'''

    -- 计划开工时间范围
    --IF (@计划开工_Start <> '')
    --    SET @whereStr = @whereStr + ' AND [计划开始时间] >= ''' + @计划开工_Start + ''''
    IF (@计划开工_End <> '')
        SET @whereStr = @whereStr + ' AND [计划开始时间] <= ''' + @计划开工_End + ''''

    -- 工位名称（支持逗号分隔的多值）
    IF (@工位名称 <> '')
    BEGIN
        -- 转义单引号防止注入（虽然 STRING_SPLIT 不直接拼接值，但安全起见）
        SET @whereStr = @whereStr + 
            ' AND [指派对象] not IN (SELECT LTRIM(RTRIM(value)) FROM STRING_SPLIT(''' + REPLACE(@工位名称, '''', '''''') + ''', '',''))'
    END

    -- 生产状态逻辑（核心修复点）
    IF (@生产状态 IS NULL OR @生产状态 = -1)
    BEGIN
	    print @生产状态
        -- 未指定状态：只查 1（可执行）、2（已开工）
        SET @whereStr = @whereStr + ' AND ISNULL(任务状态, 0) IN (0,1,2) '
    END
    ELSE IF (@生产状态 = 0)
    BEGIN
        SET @whereStr = @whereStr + ' AND ISNULL(任务状态, 0) = 0 ' -- 待执行
    END
    ELSE IF (@生产状态 = 1)
    BEGIN
        SET @whereStr = @whereStr + ' AND ISNULL(任务状态, 0) = 1 ' -- 可执行
    END
    ELSE IF (@生产状态 = 2)
    BEGIN
        SET @whereStr = @whereStr + ' AND ISNULL(任务状态, 0) = 2 ' -- 已开工
    END
    ELSE IF (@生产状态 = 4)
    BEGIN
        SET @whereStr = @whereStr + ' AND ISNULL(任务状态, 0) = 4 ' -- 已完工
    END

    -- 用户ID不为空时的并集条件
    IF (@用户ID <> '')
	BEGIN
		SET @whereStr = @whereStr + ' OR ([排产状态] = 1 AND EXISTS (
			SELECT 1 FROM STRING_SPLIT([二次派工], '','') 
			WHERE LTRIM(RTRIM(value)) = ''' + @用户ID + '''
		))'
	END

    -- 拼接最终语句
    SET @selStr = @selStr + @whereStr + ' ORDER BY [计划开始时间], 指派对象'

    -- 调试用（上线前可注释掉）
    PRINT @selStr

    EXEC sp_executesql @selStr
	
END
GO
/****** Object:  StoredProcedure [dbo].[质量管理_不合格品处置_查询]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- 质量管理_质检明细_查询
CREATE PROCEDURE [dbo].[质量管理_不合格品处置_查询]
    @质检类型 nvarchar(4000) = '10',  -- 修改为字符串类型，因为传入的是字符串
    @开始日期 datetime = NULL,
    @结束日期 datetime = NULL,
    @订单号 nvarchar(4000) = '0',     -- 修改为字符串类型，避免类型转换问题
    @合同号 nvarchar(4000) = '0',
    @零件编码 nvarchar(4000) = '0',
    @零件名称 nvarchar(4000) = '0',
	@检测人 nvarchar(4000) = '0',
    @PageCurrent int = 1,             -- 要显示的页码
    @PageSize int = 20,                -- 每页的大小(记录数)
    @PageCount int OUTPUT,             -- 总页数
    @ItemCount int OUTPUT              -- 数据总数
AS
BEGIN
    SET NOCOUNT ON;
    
    DECLARE @tbname sysname = ' [dbo].[View_质检明细] '           -- 要分页显示的表名
    DECLARE @fieldkey sysname = ' QT_AID '                       -- 用于定位记录的主键(惟一键)字段
    DECLARE @where nvarchar(4000)                                 -- 查询条件
    DECLARE @fieldshow nvarchar(1000)                             -- 要显示的字段列表
    DECLARE @fieldOrder nvarchar(1000) = ' 检测时间 DESC '        -- 排序字段
    
    -- 构建查询条件（使用参数化方式，避免SQL注入）
    SET @where = ' (1=1) '
    
    -- 质检类型过滤
    
    IF @质检类型 = '0'
        SET @where = @where + ' AND 质检类型 = ''收检'' '
    ELSE IF @质检类型 = '1'
        SET @where = @where + ' AND 质检类型 = ''终检'' '
    ELSE IF @质检类型 = '2'
        SET @where = @where + ' AND 质检类型 = ''来料检验'' '
    ELSE IF @质检类型 = '3'
        SET @where = @where + ' AND 质检类型 = ''退库检验'' '
    
    -- 订单号过滤条件（修正：使用LIKE时加引号）
    IF @订单号 <> '0'
        SET @where = @where + ' AND 计划号 LIKE ''%' + @订单号 + '%'' '
    
    -- 合同号过滤条件
    --IF @合同号 <> '0'
    --    SET @where = @where + ' AND 内部合同号 LIKE ''%' + @合同号 + '%'' '
    
    -- 零件编码过滤条件
    IF @零件编码 <> '0'
        SET @where = @where + ' AND 零件编码 LIKE ''%' + @零件编码 + '%'' '
    
    -- 零件名称过滤条件
    IF @零件名称 <> '0'
        SET @where = @where + ' AND 零件名称 LIKE ''%' + @零件名称 + '%'' '
	IF @检测人 <> '0'
        SET @where = @where + ' AND 检测人 LIKE ''%' + @检测人 + '%'' '
    
    -- 日期范围过滤（如果提供了日期参数）
    IF @开始日期 IS NOT NULL
        SET @where = @where + ' AND 检测时间 >= ''' + CONVERT(nvarchar(30), @开始日期, 120) + ''' '
    
    IF @结束日期 IS NOT NULL
        SET @where = @where + ' AND 检测时间 <= ''' + CONVERT(nvarchar(30), @结束日期, 120) + ''' '
    
    SET @fieldshow = '
          [QT_AID]
          ,[质检类型]
          ,[零件编码]
          ,[零件名称]
          ,[内部合同号]
          ,[计划号]
          ,[工序名称]
          ,[检验数量]
          ,[合格数]
          ,[不合格数]
          ,[检测人]
          ,[检测时间]
          ,[检测说明]
          ,[工位名称]
          ,[订单类型]'
    
    -- 调试用（可以注释掉）
    PRINT @where
    
    -- 执行分页存储过程
    EXEC [dbo].[sp_xt_pagesplit] 
        @tbname, 
        @fieldkey, 
        @where, 
        @fieldshow, 
        @fieldOrder, 
        @PageCurrent, 
        @PageSize, 
        @PageCount OUTPUT, 
        @ItemCount OUTPUT
END
GO
/****** Object:  StoredProcedure [dbo].[质量管理_检验标准表_查询]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[质量管理_检验标准表_查询]
    @物料编号 NVARCHAR(100) = NULL,         
    @工序名称编号 INT = NULL,               
    @检测类别编号 INT = NULL       
AS
BEGIN
    SET NOCOUNT ON;
    
    -- 查询检验标准数据
    SELECT 
        AID,
        物料编号,
       工序名称编号,
		检测类别编号,
        检测项目,
        理论值,
        上限值,
        下限值,
        测量单位,
        检验比例,
        检具,
        备注,
		创建时间,
      更新时间
    FROM YL_质量检验_检测标准
    WHERE (@物料编号 IS NULL OR 物料编号 = @物料编号)
      AND (@工序名称编号 IS NULL OR 工序名称编号 = @工序名称编号)
       AND (@检测类别编号 IS NULL OR 检测类别编号 = @检测类别编号)
    ORDER BY 物料编号, 工序名称编号, 检测类别编号;
END
GO
/****** Object:  StoredProcedure [dbo].[质量管理_检验标准表_删除]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- 删除检验标准的存储过程
CREATE PROCEDURE [dbo].[质量管理_检验标准表_删除]
    @AID INT
AS
BEGIN
    SET NOCOUNT ON;
    
    BEGIN TRY
        BEGIN TRANSACTION;
        
        -- 检查记录是否存在
        IF NOT EXISTS (SELECT 1 FROM YL_质量检验_检测标准 WHERE AID = @AID)
        BEGIN
            SELECT '0' AS result, '未找到对应的检验标准记录' AS message;
            ROLLBACK TRANSACTION;
            RETURN;
        END
        
        -- 删除记录
        DELETE FROM YL_质量检验_检测标准 WHERE AID = @AID;
        
        -- 检查是否成功删除
        IF @@ROWCOUNT = 0
        BEGIN
            SELECT '0' AS result, '删除失败，请检查记录是否存在' AS message;
            ROLLBACK TRANSACTION;
            RETURN;
        END
        
        -- 返回成功结果
        SELECT '1' AS result, '检验标准删除成功' AS message;
        
        COMMIT TRANSACTION;
    END TRY
    BEGIN CATCH
        -- 错误处理
        IF @@TRANCOUNT > 0
            ROLLBACK TRANSACTION;
            
        -- 返回错误信息
        SELECT '0' AS result, 
               '删除失败: ' + ERROR_MESSAGE() AS message,
               ERROR_NUMBER() AS error_number,
               ERROR_SEVERITY() AS error_severity,
               ERROR_STATE() AS error_state;
    END CATCH
END
GO
/****** Object:  StoredProcedure [dbo].[质量管理_检验标准表_新增]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[质量管理_检验标准表_新增]

    @物料编号 NVARCHAR(100) = NULL,
    @工序名称编号 INT = -1,
    @检测项目 NVARCHAR(500) = NULL,
    @理论值 NVARCHAR(50) = NULL,
    @上限值 NVARCHAR(50) = NULL,
    @下限值 NVARCHAR(50) = NULL,
    @测量单位 NVARCHAR(50) = NULL,
    @检验比例 NVARCHAR(50) = NULL,
    @检具 NVARCHAR(100) = NULL,
    @备注 NVARCHAR(500) = NULL,
    @检测类别编号 INT  = -1
AS
BEGIN
    SET NOCOUNT ON;
    
    BEGIN TRY
        BEGIN TRANSACTION;
        
        -- 插入检验标准数据
        INSERT INTO YL_质量检验_检测标准 (
		
            物料编号,
            工序名称编号,
            检测项目,
            理论值,
            上限值,
            下限值,
            测量单位,
            检验比例,
            检具,
            备注,
            检测类别编号,
            创建时间
        ) VALUES (
	
            @物料编号,
            @工序名称编号,
            @检测项目,
            @理论值,
            @上限值,
            @下限值,
            @测量单位,
            @检验比例,
            @检具,
            @备注,
            @检测类别编号,
            GETDATE()
        );
        
        -- 返回成功结果
        SELECT '1' AS result, '检验标准新增成功' AS message;
        
        COMMIT TRANSACTION;
    END TRY
    BEGIN CATCH
        -- 出现错误时回滚事务
        ROLLBACK TRANSACTION;
        
        -- 返回错误信息
        SELECT '0' AS result, ERROR_MESSAGE() AS message;
    END CATCH
END
GO
/****** Object:  StoredProcedure [dbo].[质量管理_检验标准表_修改]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[质量管理_检验标准表_修改]
    @AID INT,
    @物料编号 NVARCHAR(100) = NULL,
    @工序名称编号 INT = -1,
    @检测项目 NVARCHAR(500) = NULL,
    @理论值 NVARCHAR(50) = NULL,
    @上限值 NVARCHAR(50) = NULL,
    @下限值 NVARCHAR(50) = NULL,
    @测量单位 NVARCHAR(50) = NULL,
    @检验比例 NVARCHAR(50) = NULL,
    @检具 NVARCHAR(100) = NULL,
    @备注 NVARCHAR(500) = NULL,
    @检测类别编号 INT = -1
AS
BEGIN
    SET NOCOUNT ON;
    
    BEGIN TRY
        BEGIN TRANSACTION;
        
        -- 更新检验标准数据
        UPDATE YL_质量检验_检测标准
        SET 
            物料编号 = ISNULL(@物料编号, 物料编号),
            工序名称编号 = ISNULL(@工序名称编号, 工序名称编号),
            检测项目 = ISNULL(@检测项目, 检测项目),
            理论值 = ISNULL(@理论值, 理论值),
            上限值 = ISNULL(@上限值, 上限值),
            下限值 = ISNULL(@下限值, 下限值),
            测量单位 = ISNULL(@测量单位, 测量单位),
            检验比例 = ISNULL(@检验比例, 检验比例),
            检具 = ISNULL(@检具, 检具),
            备注 = ISNULL(@备注, 备注),
            检测类别编号 = ISNULL(@检测类别编号, 检测类别编号),
            更新时间 = GETDATE()
        WHERE AID = @AID;
        
        -- 检查是否有记录被更新
        IF @@ROWCOUNT = 0
        BEGIN
            -- 没有找到对应的记录
            SELECT '0' AS result, '未找到对应的检验标准记录' AS message;
        END
        ELSE
        BEGIN
            -- 返回成功结果
            SELECT '1' AS result, '检验标准更新成功' AS message;
        END
        
        COMMIT TRANSACTION;
    END TRY
    BEGIN CATCH
        -- 出现错误时回滚事务
        ROLLBACK TRANSACTION;
        
        -- 返回错误信息
        SELECT '0' AS result, ERROR_MESSAGE() AS message;
    END CATCH
END
GO
/****** Object:  StoredProcedure [dbo].[质量管理_来料检验_更新]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[质量管理_来料检验_更新]
    
	@检测类型编号 int,
    @质检类型 NVARCHAR(50),
    @零件名称 NVARCHAR(200),
    @零件编码 NVARCHAR(200),
    @计划号 int,
    @检测数量 decimal(18, 4),
    @合格数 decimal(18, 4),
    @不合格数 decimal(18, 4),
    @检测人 NVARCHAR(50),
    @检测时间 DATETIME,
    @检测说明 NVARCHAR(MAX),
	@行号 int,
	@订单类型 NVARCHAR(50),
	@到货数 decimal(18, 4),
	@放行数量 int = 0
AS
BEGIN
    SET NOCOUNT ON;
    
    -- 更新质检任务表的累计数据
    UPDATE [dbo].[质量检验_质检任务_SAP] 
    SET 合格数 = ISNULL(合格数, 0) + @合格数, 
        不合格数 = ISNULL(不合格数, 0) + @不合格数, 
        检测人 = @检测人, 
        检验时间 = @检测时间,
        备注 = @检测说明
    WHERE 订单编号 = @计划号 AND 行号 = @行号 AND 订单类型 = @订单类型

    -- 直接插入新的检验记录
    INSERT INTO [YL_MESDB].[dbo].[YL_质量检验_质检记录] (
        [检测类型编号],
        [质检类型],
        [零件名称],
        [零件编码],
        [计划号],
        [检验数量],
        [合格数],
        [不合格数],
        [检测人],
        [检测时间],
        [检测说明],
        [行号],
        [订单类型],
        [到货数],
        [放行数量]
    )
    VALUES (
        @检测类型编号,
        @质检类型,
        @零件名称,
        @零件编码,
        @计划号,
        @检测数量,
        @合格数,
        @不合格数,
        @检测人,
        @检测时间,
        @检测说明,
        @行号,
        @订单类型,
        @到货数,
        @放行数量
    );
            
    -- 返回成功状态
    SELECT 1 AS result, '检验记录保存成功' AS message
END
GO
/****** Object:  StoredProcedure [dbo].[质量管理_其他入库_查询]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE PROCEDURE [dbo].[质量管理_其他入库_查询]
    @订单号 NVARCHAR(100) = '',
    @零件编号 NVARCHAR(100) = '',
    @零件名称 NVARCHAR(100) = '',
    @检测日期_Start NVARCHAR(20) = '',
    @检测日期_End NVARCHAR(20) = '',
    @检测结果 NVARCHAR(10) = '',
    @检测人 NVARCHAR(50) = '',
	@状态 NVARCHAR(10) = '',
	@单据码 NVARCHAR(50) = ''
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @SQL NVARCHAR(MAX)
    DECLARE @WhereConditions NVARCHAR(MAX) = ''

    -- 构建WHERE条件

	SET @WhereConditions = @WhereConditions + ' AND (订单类型 = ''59'') '
	IF @单据码 <> ''
        SET @WhereConditions = @WhereConditions + ' AND 单据码 LIKE ''%' + @单据码 + '%'''
    IF @订单号 <> ''
        SET @WhereConditions = @WhereConditions + ' AND 订单编号 LIKE ''%' + @订单号 + '%'''

    IF @零件编号 <> ''
        SET @WhereConditions = @WhereConditions + ' AND 物料编码 LIKE ''%' + @零件编号 + '%'''

    IF @零件名称 <> ''
        SET @WhereConditions = @WhereConditions + ' AND 物料名称 LIKE ''%' + @零件名称 + '%'''


    -- 检测日期范围
    IF @检测日期_Start <> '' AND @检测日期_End <> ''
        SET @WhereConditions = @WhereConditions + ' AND CONVERT(DATE, 检验时间) BETWEEN ''' + @检测日期_Start + ''' AND ''' + @检测日期_End + ''''

    -- 检测结果处理（需要根据合格数和不合格数判断）
    IF @检测结果 <> ''
    BEGIN
        IF @检测结果 = '1'  -- 合格
            SET @WhereConditions = @WhereConditions + ' AND (合格数 > 0 AND 不合格数 = 0)'
        ELSE IF @检测结果 = '0'  -- 不合格
            SET @WhereConditions = @WhereConditions + ' AND ( 不合格数 > 0)'
    END
	IF @状态 <> ''
    BEGIN
        IF @状态 = '1'  -- 已完成
            SET @WhereConditions = @WhereConditions + ' AND  (ISNULL(合格数, 0) + ISNULL(不合格数, 0) = ISNULL(到货数, 0))  AND ISNULL(到货数, 0) <> 0'
        ELSE IF @状态 = '0'  -- 未完成
            SET @WhereConditions = @WhereConditions + ' AND (ISNULL(合格数, 0) + ISNULL(不合格数, 0) < ISNULL(到货数, 入库数量)) '
    END
    IF @检测人 <> ''
        SET @WhereConditions = @WhereConditions + ' AND ISNULL( 检测人, '''') LIKE ''%' + @检测人 + '%'''


    -- 移除开头的" AND "
    IF LEN(@WhereConditions) > 0
        SET @WhereConditions = ' WHERE ' + SUBSTRING(@WhereConditions, 5, LEN(@WhereConditions))

	SET @SQL = '
	SELECT 
		* from [dbo].[质量检验_质检任务_SAP] '+@WhereConditions+'' 

    -- 打印SQL语句用于调试
    PRINT @SQL
    
    -- 执行动态SQL
    EXEC sp_executesql @SQL
END
GO
/****** Object:  StoredProcedure [dbo].[质量管理_其他入库检验_更新]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[质量管理_其他入库检验_更新]
    
	@检测类型编号 int,
    @质检类型 NVARCHAR(50),
    @零件名称 NVARCHAR(200),
    @零件编码 NVARCHAR(200),
    @计划号 int,
    @检测数量 decimal(18, 4),
    @合格数 decimal(18, 4),
    @不合格数 decimal(18, 4),
    @检测人 NVARCHAR(50),
    @检测时间 DATETIME,
    @检测说明 NVARCHAR(MAX),
	@行号 int,
	@订单类型 NVARCHAR(50),
	@放行数量 int = 0
AS
BEGIN
    SET NOCOUNT ON;
    
    -- 更新质检任务表
    UPDATE [dbo].[质量检验_质检任务_SAP] 
    SET 合格数 = @合格数, 
        不合格数 = @不合格数, 
        检测人 = @检测人, 
        检验时间 = @检测时间,
		备注 = @检测说明
    WHERE 订单编号 = @计划号 AND 行号 = @行号 and  订单类型 = @订单类型

    -- 使用MERGE语句实现"没有就插入，有就更新"
    MERGE INTO [YL_MESDB].[dbo].[YL_质量检验_质检记录] AS target
    USING (SELECT 
            @检测类型编号 AS 检测类型编号,
            @质检类型 AS 质检类型,
            @零件名称 AS 零件名称,
            @零件编码 AS 零件编码,
            @计划号 AS 计划号,
            @检测数量 AS 检验数量,
            @合格数 AS 合格数,
            @不合格数 AS 不合格数,
            @检测人 AS 检测人,
            @检测时间 AS 检测时间,
            @检测说明 AS 检测说明,
            @行号 AS 行号,
            @订单类型 AS 订单类型,
			@放行数量 AS 放行数量
          ) AS source
    ON (target.[零件编码] = source.[零件编码] AND target.[计划号] = source.[计划号] and target.行号 = source.行号 )
    WHEN MATCHED THEN
        UPDATE SET 
            target.[检测类型编号] = source.[检测类型编号],
            target.[质检类型] = source.[质检类型],
            target.[零件名称] = source.[零件名称],
            target.[检验数量] = source.[检验数量],
            target.[合格数] = source.[合格数],
            target.[不合格数] = source.[不合格数],
            target.[检测人] = source.[检测人],
            target.[检测时间] = source.[检测时间],
            target.[检测说明] = source.[检测说明],
            target.[行号] = source.[行号],
            target.[订单类型] = source.[订单类型],
			target.[放行数量] = source.[放行数量]
    WHEN NOT MATCHED THEN
        INSERT (
            [检测类型编号],
            [质检类型],
            [零件名称],
            [零件编码],
            [计划号],
            [检验数量],
            [合格数],
            [不合格数],
            [检测人],
            [检测时间],
            [检测说明],
            [行号],
            [订单类型],
			放行数量
        )
        VALUES (
            source.[检测类型编号],
            source.[质检类型],
            source.[零件名称],
            source.[零件编码],
            source.[计划号],
            source.[检验数量],
            source.[合格数],
            source.[不合格数],
            source.[检测人],
            source.[检测时间],
            source.[检测说明],
            source.[行号],
            source.[订单类型],
			source.[放行数量]
        );
            
END
GO
/****** Object:  StoredProcedure [dbo].[质量管理_销售退货检_更新]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[质量管理_销售退货检_更新]
    
	@检测类型编号 int,
    @质检类型 NVARCHAR(50),
    @零件名称 NVARCHAR(200),
    @零件编码 NVARCHAR(200),
    @计划号 int,
    @检测数量 decimal(18, 4),
    @合格数 decimal(18, 4),
    @不合格数 decimal(18, 4),
    @检测人 NVARCHAR(50),
    @检测时间 DATETIME,
    @检测说明 NVARCHAR(MAX),
	@行号 int,
	@订单类型 NVARCHAR(50)
	
AS
BEGIN
    SET NOCOUNT ON;
    
    -- 更新质检任务表
    UPDATE [dbo].[质量检验_质检任务_SAP] 
    SET 合格数 = @合格数, 
        不合格数 = @不合格数, 
        检测人 = @检测人, 
        检验时间 = @检测时间,
		备注 = @检测说明
    WHERE 订单编号 = @计划号 AND 行号 = @行号  and  订单类型 = @订单类型

    -- 使用MERGE语句实现"没有就插入，有就更新"
    MERGE INTO [YL_MESDB].[dbo].[YL_质量检验_质检记录] AS target
    USING (SELECT 
            @检测类型编号 AS 检测类型编号,
            @质检类型 AS 质检类型,
            @零件名称 AS 零件名称,
            @零件编码 AS 零件编码,
            @计划号 AS 计划号,
            @检测数量 AS 检验数量,
            @合格数 AS 合格数,
            @不合格数 AS 不合格数,
            @检测人 AS 检测人,
            @检测时间 AS 检测时间,
            @检测说明 AS 检测说明,
            @行号 AS 行号,
            @订单类型 AS 订单类型
          ) AS source
    ON (target.[零件编码] = source.[零件编码] AND target.[计划号] = source.[计划号] and target.行号 = source.行号 )
    WHEN MATCHED THEN
        UPDATE SET 
            target.[检测类型编号] = source.[检测类型编号],
            target.[质检类型] = source.[质检类型],
            target.[零件名称] = source.[零件名称],
            target.[检验数量] = source.[检验数量],
            target.[合格数] = source.[合格数],
            target.[不合格数] = source.[不合格数],
            target.[检测人] = source.[检测人],
            target.[检测时间] = source.[检测时间],
            target.[检测说明] = source.[检测说明],
            target.[行号] = source.[行号],
            target.[订单类型] = source.[订单类型]
    WHEN NOT MATCHED THEN
        INSERT (
            [检测类型编号],
            [质检类型],
            [零件名称],
            [零件编码],
            [计划号],
            [检验数量],
            [合格数],
            [不合格数],
            [检测人],
            [检测时间],
            [检测说明],
            [行号],
            [订单类型]
        )
        VALUES (
            source.[检测类型编号],
            source.[质检类型],
            source.[零件名称],
            source.[零件编码],
            source.[计划号],
            source.[检验数量],
            source.[合格数],
            source.[不合格数],
            source.[检测人],
            source.[检测时间],
            source.[检测说明],
            source.[行号],
            source.[订单类型]
        );
            
END
GO
/****** Object:  StoredProcedure [dbo].[质量管理_序检收检_更新]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[质量管理_序检收检_更新]
    @TaskAID bigint,
	@检测类型编号 int,
    @质检类型 NVARCHAR(50),
    @零件名称 NVARCHAR(200),
    @内部合同号 int,
    @零件编码 NVARCHAR(200),
    @计划号 int,
    @工序名称 NVARCHAR(100),
    @检测数量 INT,
    @合格数 INT,
    @不合格数 INT,
    @检测人 NVARCHAR(50),
    @检测时间 DATETIME,
    @计划生产数 INT,
    @检测说明 NVARCHAR(MAX)
AS
BEGIN
    SET NOCOUNT ON;

    BEGIN TRY
        BEGIN TRANSACTION;

        -- 更新现有记录而不是插入新记录
        UPDATE [YL_MESDB].[dbo].[YL_质量检验_质检记录] 
        SET 
            [检测类型编号] = @检测类型编号,
            [质检类型] = @质检类型,
            [零件名称] = @零件名称,
            [内部合同号] = @内部合同号,
            [零件编码] = @零件编码,
            [计划号] = @计划号,
            [工序名称] = @工序名称,
            [检验数量] = @检测数量,
            [合格数] = @合格数,
            [不合格数] = @不合格数,
            [检测人] = @检测人,
            [检测时间] = @检测时间,
            [计划生产数] = @计划生产数,
            [检测说明] = @检测说明
        WHERE 
            [TaskAID] = @TaskAID

        -- 检查是否成功更新了记录
        IF @@ROWCOUNT = 0
        BEGIN
            RAISERROR('未找到对应的记录进行更新', 16, 1)
        END

        -- 获取当前任务的订单行号
        DECLARE @当前订单行号 INT
        SELECT @当前订单行号 = ISNULL(订单行号, 0) 
        FROM [dbo].[MES_接口_生产计划_生产任务] 
        WHERE AID = @TaskAID

        -- 计算同一订单号且同一订单行号的所有收检任务的合格数总和
        DECLARE @总合格数 INT
        SELECT @总合格数 = ISNULL(SUM(qc.合格数), 0) 
        FROM [YL_MESDB].[dbo].[YL_质量检验_质检记录] qc
        INNER JOIN [dbo].[MES_接口_生产计划_生产任务] task ON qc.TaskAID = task.AID
        WHERE task.订单编号 = @计划号 
          AND task.订单行号 = @当前订单行号

        -- 查找下一道工序：同一个订单号、订单行号+1、拆分内码=1的任务
        DECLARE @下一道工序AID INT
        SELECT @下一道工序AID = AID 
        FROM [dbo].[MES_接口_生产计划_生产任务] 
        WHERE 订单编号 = @计划号 
          AND 订单行号 = @当前订单行号 + 1 
          AND ISNULL(订单拆分内码, 1) = 1

        -- 查找下一道工序中拆分内码>1的所有任务
        DECLARE @拆分内码大于1的任务数 INT

        -- 更新拆分内码>1的任务，指派数量设置为0
        UPDATE [dbo].[MES_接口_生产计划_生产任务] 
        SET 指派数量 = 0 
        WHERE 订单编号 = @计划号 
          AND 订单行号 = @当前订单行号 + 1 
          AND ISNULL(订单拆分内码, 0) > 1

        SELECT @拆分内码大于1的任务数 = @@ROWCOUNT

        -- 如果找到下一道工序（拆分内码=1），则更新其指派数量为总合格数
        IF @下一道工序AID IS NOT NULL
        BEGIN
            UPDATE [dbo].[MES_接口_生产计划_生产任务] 
            SET 指派数量 = @总合格数, 任务状态 = 1
            WHERE AID = @下一道工序AID
        END

        COMMIT TRANSACTION;

        -- 返回操作结果
        SELECT '1' AS result, 
               '操作成功' AS message,
               @总合格数 AS 总合格数,
               ISNULL(@下一道工序AID, 0) AS 下一道工序AID,
               @拆分内码大于1的任务数 AS 清零任务数

    END TRY
    BEGIN CATCH
        IF @@TRANCOUNT > 0
            ROLLBACK TRANSACTION;
        
        -- 返回错误信息
        SELECT '0' AS result, 
               '操作失败: ' + ERROR_MESSAGE() AS message,
               0 AS 总合格数,
               0 AS 下一道工序AID,
               0 AS 清零任务数
    END CATCH
END
GO
/****** Object:  StoredProcedure [dbo].[质量管理_序检收检_新增]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- 创建存储过程 MES_QulityInspection_ReceiveCheck
CREATE PROCEDURE [dbo].[质量管理_序检收检_新增]
    @TaskAID bigint,
	@检测类型编号 int,
    @质检类型 NVARCHAR(50),
    @零件名称 NVARCHAR(200),
    @内部合同号 int,
    @零件编码 NVARCHAR(200),
    @计划号 int,
    @工序名称 NVARCHAR(100),
    @检测数量 INT,
    @合格数 INT,
    @不合格数 INT,
    @检测人 NVARCHAR(50),
    @检测时间 DATETIME,
    @检测说明 NVARCHAR(MAX),
	@放行数量 INT = 0
AS
BEGIN
    SET NOCOUNT ON;

    BEGIN TRY
        BEGIN TRANSACTION;
		DECLARE @最新检测数量 int
		DECLARE @已完成检测数量 int
		DECLARE @计划数量 int
		select @计划数量 = 计划数量 from [dbo].[MES_接口_生产计划_生产任务] where  AID = @TaskAID
		select @已完成检测数量 = sum(检验数量) from YL_质量检验_质检记录 where  [TaskAID] = @TaskAID  and  质检类型 = '收检'
		set @最新检测数量 = @检测数量 + isnull(@已完成检测数量,0)
		print @最新检测数量
		print @计划数量
		if @最新检测数量 <= @计划数量

		BEGIN
        -- 插入新记录
			INSERT INTO [YL_MESDB].[dbo].[YL_质量检验_质检记录] (
				[TaskAID],
				[检测类型编号],
				[质检类型],
				[零件名称],
				[内部合同号],
				[零件编码],
				[计划号],
				[工序名称],
				[检验数量],
				[合格数],
				[不合格数],
				[检测人],
				[检测时间],
				[检测说明],
				放行数量
			)
			VALUES (
				@TaskAID,
				@检测类型编号,
				@质检类型,
				@零件名称,
				@内部合同号,
				@零件编码,
				@计划号,
				@工序名称,
				@检测数量,
				@合格数,
				@不合格数,
				@检测人,
				@检测时间,
				@检测说明,
				@放行数量
			)
		END
        -- 获取当前任务的订单行号
        DECLARE @当前订单行号 INT
        SELECT @当前订单行号 = ISNULL(订单行号, 0) 
        FROM [dbo].[MES_接口_生产计划_生产任务] 
        WHERE AID = @TaskAID

    --    -- 计算同一订单号且同一订单行号的所有收检任务的合格数总和
    --    DECLARE @总合格数 INT
    --    SELECT @总合格数 = ISNULL(SUM(qc.合格数), 0) 
    --    FROM [YL_MESDB].[dbo].[YL_质量检验_质检记录] qc
    --    INNER JOIN [dbo].[MES_接口_生产计划_生产任务] task ON qc.TaskAID = task.AID
    --    WHERE task.订单编号 = @计划号 
    --      AND task.订单行号 = @当前订单行号
		  --AND qc.质检类型 = '收检'
        -- 查找下一道工序：同一个订单号、订单行号+1、拆分内码=1的任务
        DECLARE @下一道工序AID INT
        SELECT @下一道工序AID = AID 
        FROM [dbo].[MES_接口_生产计划_生产任务] 
        WHERE 订单编号 = @计划号 
          AND 订单行号 = @当前订单行号 + 1 
          AND ISNULL(订单拆分内码, 1) = 1

        ---- 查找下一道工序中拆分内码>1的所有任务
        --DECLARE @拆分内码大于1的任务数 INT

        ---- 更新拆分内码>1的任务，指派数量设置为0
        --UPDATE [dbo].[MES_接口_生产计划_生产任务] 
        --SET 任务状态 = 1
        --WHERE 订单编号 = @计划号 
        --  AND 订单行号 = @当前订单行号 + 1 
        --  AND ISNULL(订单拆分内码, 0) > 1

        --SELECT @拆分内码大于1的任务数 = @@ROWCOUNT

        -- 如果找到下一道工序（拆分内码=1），则更新其指派数量为总合格数
        IF @下一道工序AID IS NOT NULL
        BEGIN
            UPDATE [dbo].[MES_接口_生产计划_生产任务] 
            SET 任务状态 = 1
            WHERE AID = @下一道工序AID
        END

        COMMIT TRANSACTION;

        ---- 返回操作结果
        SELECT '1' AS result, 
               '操作成功' AS message
        --       @总合格数 AS 总合格数,
        --       ISNULL(@下一道工序AID, 0) AS 下一道工序AID,
        --       @拆分内码大于1的任务数 AS 清零任务数

    END TRY
    BEGIN CATCH
        IF @@TRANCOUNT > 0
            ROLLBACK TRANSACTION;
        
        -- 返回错误信息
        SELECT '0' AS result, 
               '操作失败: ' + ERROR_MESSAGE() AS message,
               0 AS 总合格数,
               0 AS 下一道工序AID,
               0 AS 清零任务数
    END CATCH
END
GO
/****** Object:  StoredProcedure [dbo].[质量管理_原材料退库_查询]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE PROCEDURE [dbo].[质量管理_原材料退库_查询]
    @订单号 NVARCHAR(100) = '',
    @零件编号 NVARCHAR(100) = '',
    @零件名称 NVARCHAR(100) = '',
    @检测日期_Start NVARCHAR(20) = '',
    @检测日期_End NVARCHAR(20) = '',
    @检测结果 NVARCHAR(10) = '',
    @检测人 NVARCHAR(50) = '',
	@状态 NVARCHAR(10) = '',
	@单据码 NVARCHAR(50) = ''
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @SQL NVARCHAR(MAX)
    DECLARE @WhereConditions NVARCHAR(MAX) = ''

    -- 构建WHERE条件

	SET @WhereConditions = @WhereConditions + ' AND (订单类型 = ''202-60'') '
	IF @单据码 <> ''
        SET @WhereConditions = @WhereConditions + ' AND 单据码 LIKE ''%' + @单据码 + '%'''
    IF @订单号 <> ''
        SET @WhereConditions = @WhereConditions + ' AND 订单编号 LIKE ''%' + @订单号 + '%'''

    IF @零件编号 <> ''
        SET @WhereConditions = @WhereConditions + ' AND 物料编码 LIKE ''%' + @零件编号 + '%'''

    IF @零件名称 <> ''
        SET @WhereConditions = @WhereConditions + ' AND 物料名称 LIKE ''%' + @零件名称 + '%'''


    -- 检测日期范围
    IF @检测日期_Start <> '' AND @检测日期_End <> ''
        SET @WhereConditions = @WhereConditions + ' AND CONVERT(DATE, 检验时间) BETWEEN ''' + @检测日期_Start + ''' AND ''' + @检测日期_End + ''''

    -- 检测结果处理（需要根据合格数和不合格数判断）
    IF @检测结果 <> ''
    BEGIN
        IF @检测结果 = '1'  -- 合格
            SET @WhereConditions = @WhereConditions + ' AND (合格数 > 0 AND 不合格数 = 0)'
        ELSE IF @检测结果 = '0'  -- 不合格
            SET @WhereConditions = @WhereConditions + ' AND ( 不合格数 > 0)'
    END
	IF @状态 <> ''
    BEGIN
        IF @状态 = '1'  -- 已完成
            SET @WhereConditions = @WhereConditions + ' AND  (ISNULL(合格数, 0) + ISNULL(不合格数, 0) = ISNULL(到货数, 0))  AND ISNULL(到货数, 0) <> 0'
        ELSE IF @状态 = '0'  -- 未完成
            SET @WhereConditions = @WhereConditions + ' AND (ISNULL(合格数, 0) + ISNULL(不合格数, 0) < ISNULL(到货数, 入库数量)) '
    END
    IF @检测人 <> ''
        SET @WhereConditions = @WhereConditions + ' AND ISNULL( 检测人, '''') LIKE ''%' + @检测人 + '%'''


    -- 移除开头的" AND "
    IF LEN(@WhereConditions) > 0
        SET @WhereConditions = ' WHERE ' + SUBSTRING(@WhereConditions, 5, LEN(@WhereConditions))

	SET @SQL = '
	SELECT 
		* from [dbo].[质量检验_质检任务_SAP] '+@WhereConditions+'' 

    -- 打印SQL语句用于调试
    PRINT @SQL
    
    -- 执行动态SQL
    EXEC sp_executesql @SQL
END
GO
/****** Object:  StoredProcedure [dbo].[质量管理_原材料退库检验_更新]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[质量管理_原材料退库检验_更新]
    
	@检测类型编号 int,
    @质检类型 NVARCHAR(50),
    @零件名称 NVARCHAR(200),
    @零件编码 NVARCHAR(200),
    @计划号 int,
    @检测数量 decimal(18, 4),
    @合格数 decimal(18, 4),
    @不合格数 decimal(18, 4),
    @检测人 NVARCHAR(50),
    @检测时间 DATETIME,
    @检测说明 NVARCHAR(MAX),
	@行号 int,
	@订单类型 NVARCHAR(50),
	@到货数 decimal(18, 4),
	@放行数量 int = 0
AS
BEGIN
    SET NOCOUNT ON;
    
    -- 更新质检任务表
    UPDATE [dbo].[质量检验_质检任务_SAP] 
    SET 合格数 = @合格数, 
        不合格数 = @不合格数, 
        检测人 = @检测人, 
        检验时间 = @检测时间,
        到货数 = @到货数,
		备注 = @检测说明

    WHERE 订单编号 = @计划号 AND 行号 = @行号 and  订单类型 = @订单类型

    -- 使用MERGE语句实现"没有就插入，有就更新"
    MERGE INTO [YL_MESDB].[dbo].[YL_质量检验_质检记录] AS target
    USING (SELECT 
            @检测类型编号 AS 检测类型编号,
            @质检类型 AS 质检类型,
            @零件名称 AS 零件名称,
            @零件编码 AS 零件编码,
            @计划号 AS 计划号,
            @检测数量 AS 检验数量,
            @合格数 AS 合格数,
            @不合格数 AS 不合格数,
            @检测人 AS 检测人,
            @检测时间 AS 检测时间,
            @检测说明 AS 检测说明,
            @行号 AS 行号,
            @订单类型 AS 订单类型,
            @到货数 AS 到货数,
			@放行数量 AS 放行数量
          ) AS source
    ON (target.[零件编码] = source.[零件编码] AND target.[计划号] = source.[计划号] and target.行号 = source.行号 )
    WHEN MATCHED THEN
        UPDATE SET 
            target.[检测类型编号] = source.[检测类型编号],
            target.[质检类型] = source.[质检类型],
            target.[零件名称] = source.[零件名称],
            target.[检验数量] = source.[检验数量],
            target.[合格数] = source.[合格数],
            target.[不合格数] = source.[不合格数],
            target.[检测人] = source.[检测人],
            target.[检测时间] = source.[检测时间],
            target.[检测说明] = source.[检测说明],
            target.[行号] = source.[行号],
            target.[订单类型] = source.[订单类型],
            target.[到货数] = source.[到货数],
			target.放行数量 = source.放行数量
			
    WHEN NOT MATCHED THEN
        INSERT (
            [检测类型编号],
            [质检类型],
            [零件名称],
            [零件编码],
            [计划号],
            [检验数量],
            [合格数],
            [不合格数],
            [检测人],
            [检测时间],
            [检测说明],
            [行号],
            [订单类型],
            [到货数],
			放行数量
        )
        VALUES (
            source.[检测类型编号],
            source.[质检类型],
            source.[零件名称],
            source.[零件编码],
            source.[计划号],
            source.[检验数量],
            source.[合格数],
            source.[不合格数],
            source.[检测人],
            source.[检测时间],
            source.[检测说明],
            source.[行号],
            source.[订单类型],
            source.[到货数],
			source.放行数量
        );
            
END
GO
/****** Object:  StoredProcedure [dbo].[质量管理_质检报工_任务查询]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [dbo].[质量管理_质检报工_任务查询]
	@TaskAID int =-1,
    @订单号 int = -1,
    @零件编号 nvarchar(50) = '',
    @计划开工_Start nvarchar(50) = '',
    @计划开工_End nvarchar(50) = '',
    @生产状态 int = -1,	-- -1: 未指定；0: 待执行；1: 可执行；2: 已开工；4: 已完工
    @工位名称 nvarchar(50) = '',
	@用户ID nvarchar(50) = '',
	@计划号 nvarchar(50) = '',
	@销售订单 nvarchar(50) = '',
	@送检 int = 1
AS
BEGIN
    DECLARE @whereStr nvarchar(max) = ' WHERE main.排产状态 = 1 '
    DECLARE @selStr nvarchar(max) = 
    'SELECT 
			main.TaskAID,
			main.本次检数,
            main.[订单编号] as 订单号,
			main.合同号,
			main.自制件属性,
			main.加急总数,
			main.派工特殊说明,
            main.[订单拆分内码],
            main.[订单行号],
            main.[开工时间],
            main.[物料编号] as 零件编码,
            main.[物料描述] as 零件名称,
            case when isnull(main.[加急状态],0)=1 then ''加急'' else ''否'' end as [加急],
            main.[优先级] as [优先],
            main.[指派对象编号],
            main.[指派对象],
            main.[工序名称],
			main.[二次派工],
			main.[计划号],
            isnull(main.[指派数量],0) as 分配数,
            main.[计划开始时间] as 计划开始,
            main.[计划完成时间] as 计划完成,
            main.[最晚开始时间] as 最晚开始,
            isnull(main.[收料数量],0) as 收料,
            isnull(main.[完成数量],0) as 完成数量,
			case 
                when isnull(main.齐套,0)=1 then ''是'' 
                when isnull(main.齐套,0)=0 then ''否''
			end as [齐套],
			case 
                when isnull(main.发料状态,0)=1 then ''发料齐套'' 
                when isnull(main.发料状态,0)=2 then ''发料缺件''
			end as [发料状态],
			case 
                when isnull(main.拣配状态,0)=1 then ''已拣配'' 
                when isnull(main.拣配状态,0)=0 then ''未拣配''
			end as [拣配状态],
            case 
                when isnull(main.任务状态,0)=4 then ''已完成'' 
                when isnull(main.任务状态,0)=2 then ''已开工'' 
                when isnull(main.任务状态,0)=0 then ''待执行'' 
                when isnull(main.任务状态,0)=1 then ''可执行''
                else '''' 
            end as [任务状态],
            case 
                when isnull(main.加工状态,0)=2 then ''辅助开始''
                when isnull(main.加工状态,0)=3 then ''辅助结束''
                when isnull(main.加工状态,0)=4 then ''开始加工''
                when isnull(main.加工状态,0)=5 then ''暂停''
                when isnull(main.加工状态,0)=6 then ''报工''
                else '''' 
            end as [加工状态],
            isnull(main.加工状态,0) as 加工状态编号,
            case when isnull(main.[首检],-1)=1 then ''OK'' when isnull(main.[首检],-1)=0 then ''NG'' else '''' end as [首检],
            case when isnull(main.[序检],-1)=1 then ''OK'' when isnull(main.[序检],-1)=0 then ''NG'' else '''' end as [序检],
			ISNULL(上序统计.上序合格数, 0) as 上序合格数,
			ISNULL(质检统计.合格数, 0) as 合格数,
			ISNULL(质检统计.检验数量, 0) as 检验数量
     FROM [View_生产订单_MES] AS main
     LEFT JOIN (
		SELECT 
			b.订单编号,
			b.订单行号,
			SUM(ISNULL(a.合格数, 0)) as 合格数,
			SUM(ISNULL(a.检验数量, 0)) as 检验数量
		FROM [dbo].[YL_质量检验_质检记录] as a 
		INNER JOIN [dbo].[MES_接口_生产计划_生产任务] as b ON a.TaskAID = b.AID
		WHERE a.检测类型编号 = 6
		GROUP BY b.订单编号, b.订单行号
	) AS 质检统计 ON main.订单编号 = 质检统计.订单编号 AND main.订单行号 = 质检统计.订单行号
	LEFT JOIN (
		SELECT 
			b.订单编号,
			b.订单行号,
			SUM(ISNULL(a.合格数, 0)) as 上序合格数
		FROM [dbo].[YL_质量检验_质检记录] as a 
		INNER JOIN [dbo].[MES_接口_生产计划_生产任务] as b ON a.TaskAID = b.AID
		WHERE a.检测类型编号 = 6
		GROUP BY b.订单编号, b.订单行号
	) AS 上序统计 ON main.订单编号 = 上序统计.订单编号 AND main.订单行号 = 上序统计.订单行号 + 1'

    -- 基础过滤：排除外协
    SET @whereStr = @whereStr + ' AND main.[指派对象] <> ''外协'' AND main.[指派对象] LIKE ''%装配%'''

    -- 订单号
    IF (@订单号 > 0)
        SET @whereStr = @whereStr + ' AND main.[订单编号] = ' + CONVERT(VARCHAR(10), @订单号)
	IF (@计划号 > 0)
        SET @whereStr = @whereStr + ' AND main.[计划号] = '''+@计划号+'''' 
	IF (@销售订单<> '')
        SET @whereStr = @whereStr + ' AND main.[合同号] LIKE ''%' + @销售订单 + '%''' 
	IF (@TaskAID > 0)
        SET @whereStr = @whereStr + ' AND main.[TaskAID] = ' + CONVERT(VARCHAR(10), @TaskAID)
	IF (@送检 = 1)
        SET @whereStr = @whereStr + ' AND ISNULL(main.完成数量, 0) > 0 ' 
	IF (@送检 = 2)
        SET @whereStr = @whereStr + ' AND ISNULL(main.完成数量, 0) = 0 ' 
    -- 零件编号（模糊）
    IF (@零件编号 <> '')
        SET @whereStr = @whereStr + ' AND main.[物料编号] LIKE ''%' + @零件编号 + '%'''

    -- 计划开工时间范围
    IF (@计划开工_Start <> '')
        SET @whereStr = @whereStr + ' AND main.[计划开始时间] >= ''' + @计划开工_Start + ''''
    IF (@计划开工_End <> '')
        SET @whereStr = @whereStr + ' AND main.[计划开始时间] <= ''' + @计划开工_End + ''''

    -- 工位名称（支持逗号分隔的多值）
    IF (@工位名称 <> '')
    BEGIN
        -- 转义单引号防止注入（虽然 STRING_SPLIT 不直接拼接值，但安全起见）
        SET @whereStr = @whereStr + 
            ' AND main.[指派对象] IN (SELECT LTRIM(RTRIM(value)) FROM STRING_SPLIT(''' + REPLACE(@工位名称, '''', '''''') + ''', '',''))'
    END

    -- 生产状态逻辑（核心修复点）
    IF (@生产状态 IS NULL OR @生产状态 = -1)
    BEGIN
	    print @生产状态
        -- 未指定状态：只查 1（可执行）、2（已开工）
        SET @whereStr = @whereStr + ' AND ISNULL(main.任务状态, 0) IN (0,1,2) '
    END
    ELSE IF (@生产状态 = 0)
    BEGIN
        SET @whereStr = @whereStr + ' AND ISNULL(main.任务状态, 0) = 0 ' -- 待执行
    END
    ELSE IF (@生产状态 = 1)
    BEGIN
        SET @whereStr = @whereStr + ' AND ISNULL(main.任务状态, 0) = 1 ' -- 可执行
    END
    ELSE IF (@生产状态 = 2)
    BEGIN
        SET @whereStr = @whereStr + ' AND ISNULL(main.任务状态, 0) = 2 ' -- 已开工
    END
    ELSE IF (@生产状态 = 4)
    BEGIN
        SET @whereStr = @whereStr + ' AND ISNULL(main.任务状态, 0) = 4 ' -- 已完工
    END

    -- 用户ID不为空时的并集条件
    IF (@用户ID <> '')
	BEGIN
		SET @whereStr = @whereStr + ' OR (main.[排产状态] = 1 AND EXISTS (
			SELECT 1 FROM STRING_SPLIT(main.[二次派工], '','') 
			WHERE LTRIM(RTRIM(value)) = ''' + @用户ID + '''
		))'
	END

    -- 拼接最终语句
    SET @selStr = @selStr + @whereStr + ' ORDER BY main.[计划开始时间], main.[订单编号], main.[阶段标识]'

    -- 调试用（上线前可注释掉）
    PRINT @selStr

    EXEC sp_executesql @selStr
	
END
GO
/****** Object:  StoredProcedure [dbo].[质量管理_质检明细_查询]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- 质量管理_质检明细_查询
CREATE PROCEDURE [dbo].[质量管理_质检明细_查询]
    @质检类型 nvarchar(4000) = '10',  -- 修改为字符串类型，因为传入的是字符串
    @开始日期 datetime = NULL,
    @结束日期 datetime = NULL,
    @订单号 nvarchar(4000) = '0',     -- 修改为字符串类型，避免类型转换问题
    @合同号 nvarchar(4000) = '0',
    @零件编码 nvarchar(4000) = '0',
    @零件名称 nvarchar(4000) = '0',
    @PageCurrent int = 1,             -- 要显示的页码
    @PageSize int = 20,                -- 每页的大小(记录数)
    @PageCount int OUTPUT,             -- 总页数
    @ItemCount int OUTPUT              -- 数据总数
AS
BEGIN
    SET NOCOUNT ON;
    
    DECLARE @tbname sysname = ' [dbo].[View_质检明细] '           -- 要分页显示的表名
    DECLARE @fieldkey sysname = ' '                       -- 用于定位记录的主键(惟一键)字段
    DECLARE @where nvarchar(4000)                                 -- 查询条件
    DECLARE @fieldshow nvarchar(1000)                             -- 要显示的字段列表
    DECLARE @fieldOrder nvarchar(1000) = ' 检测时间 DESC '        -- 排序字段
    
    -- 构建查询条件（使用参数化方式，避免SQL注入）
    SET @where = ' (1=1) '
    
    -- 质检类型过滤
    IF @质检类型 = '10'  -- 全部
        SET @where = @where + ' AND (1=1) '
    ELSE IF @质检类型 = '0'
        SET @where = @where + ' AND 质检类型 = ''收检'' '
    ELSE IF @质检类型 = '1'
        SET @where = @where + ' AND 质检类型 = ''终检'' '
    ELSE IF @质检类型 = '2'
        SET @where = @where + ' AND 质检类型 = ''来料检验'' '
    ELSE IF @质检类型 = '3'
        SET @where = @where + ' AND 质检类型 = ''退库检验'' '
    
    -- 订单号过滤条件（修正：使用LIKE时加引号）
    IF @订单号 <> '0'
        SET @where = @where + ' AND 计划号 LIKE ''%' + @订单号 + '%'' '
    
    -- 合同号过滤条件
    --IF @合同号 <> '0'
    --    SET @where = @where + ' AND 内部合同号 LIKE ''%' + @合同号 + '%'' '
    
    -- 零件编码过滤条件
    IF @零件编码 <> '0'
        SET @where = @where + ' AND 零件编码 LIKE ''%' + @零件编码 + '%'' '
    
    -- 零件名称过滤条件
    IF @零件名称 <> '0'
        SET @where = @where + ' AND 零件名称 LIKE ''%' + @零件名称 + '%'' '
    
    -- 日期范围过滤（如果提供了日期参数）
    IF @开始日期 IS NOT NULL
        SET @where = @where + ' AND 检测时间 >= ''' + CONVERT(nvarchar(30), @开始日期, 120) + ''' '
    
    IF @结束日期 IS NOT NULL
        SET @where = @where + ' AND 检测时间 <= ''' + CONVERT(nvarchar(30), @结束日期, 120) + ''' '
    
    SET @fieldshow = '
          [QT_AID]
          ,[质检类型]
          ,[零件编码]
          ,[零件名称]
          ,[内部合同号]
          ,[计划号]
          ,[工序名称]
          ,[检验数量]
          ,[合格数]
          ,[不合格数]
          ,[检测人]
          ,[检测时间]
          ,[检测说明]
          ,[工位名称]
          ,[订单类型]'
    
    -- 调试用（可以注释掉）
    PRINT @where
    
    -- 执行分页存储过程
    EXEC [dbo].[sp_xt_pagesplit] 
        @tbname, 
        @fieldkey, 
        @where, 
        @fieldshow, 
        @fieldOrder, 
        @PageCurrent, 
        @PageSize, 
        @PageCount OUTPUT, 
        @ItemCount OUTPUT
END
GO
/****** Object:  StoredProcedure [dbo].[质量管理_质检明细_导出]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[质量管理_质检明细_导出]
    @质检类型 nvarchar(4000) = '10',  -- 修改为字符串类型，因为传入的是字符串
    @开始日期 datetime = NULL,
    @结束日期 datetime = NULL,
    @订单号 nvarchar(4000) = '0',     -- 修改为字符串类型，避免类型转换问题
    @合同号 nvarchar(4000) = '0',
    @零件编码 nvarchar(4000) = '0',
    @零件名称 nvarchar(4000) = '0'
AS
BEGIN
    SET NOCOUNT ON;

    -- 导出文件名和类型
    SELECT '质检明细_' + REPLACE(REPLACE(REPLACE(CONVERT(NVARCHAR(19), GETDATE(), 21), ':', ''), '-', ''), ' ', '-') AS tablename, '15' AS tabletype
    
    -- 字段宽度
    SELECT 256*12 AS 质检类型, 256*40 AS 零件编码, 256*20 AS 零件名称, 256*12 AS 内部合同号, 256*12 AS 计划号, 
           256*15 AS 工序名称, 256*15 AS 检验数量, 256*10 AS 合格数, 256*25 AS 不合格数, 256*12 AS 检测人, 256*10 AS 工位名称,
		   256*20 AS 检测时间, 256*20 AS 检测说明
    
    -- 是否计算列
    SELECT 0 AS 质检类型, 0 AS 零件编码, 0 AS 零件名称, 0 AS 内部合同号, 0 AS 计划号, 
           0 AS 工序名称, 0 AS 检验数量, 0 AS 合格数, 0 AS 不合格数, 0 AS 检测人, 0 AS 工位名称,
		   0 AS 检测时间, 0 AS 检测说明

    -- 导出数据：每行都填满完整信息
	DECLARE @where nvarchar(max) = ' where '
    DECLARE @selStr nvarchar(max) = 
    'SELECT 
        
          [质检类型]
          ,[零件编码]
          ,[零件名称]
          ,[内部合同号]
          ,[计划号]
          ,[工序名称]
          ,[检验数量]
          ,[合格数]
          ,[不合格数]
          ,[检测人]
		  ,[工位名称]
          ,[检测时间]
          ,[检测说明]
    FROM [dbo].[View_质检明细]'

   
    
    -- 质检类型过滤
    IF @质检类型 = '10'  -- 全部
        SET @where = @where + '  (1=1) '
    ELSE IF @质检类型 = '0'
        SET @where = @where + ' AND 质检类型 = ''收检'' '
    ELSE IF @质检类型 = '1'
        SET @where = @where + ' AND 质检类型 = ''终检'' '
    ELSE IF @质检类型 = '2'
        SET @where = @where + ' AND 质检类型 = ''来料检验'' '
    ELSE IF @质检类型 = '3'
        SET @where = @where + ' AND 质检类型 = ''退库检验'' '
    
    -- 订单号过滤条件（修正：使用LIKE时加引号）
    IF @订单号 <> '0'
        SET @where = @where + ' AND 计划号 LIKE ''%' + @订单号 + '%'' '
    
    -- 合同号过滤条件
    --IF @合同号 <> '0'
    --    SET @where = @where + ' AND 内部合同号 LIKE ''%' + @合同号 + '%'' '
    
    -- 零件编码过滤条件
    IF @零件编码 <> '0'
        SET @where = @where + ' AND 零件编码 LIKE ''%' + @零件编码 + '%'' '
    
    -- 零件名称过滤条件
    IF @零件名称 <> '0'
        SET @where = @where + ' AND 零件名称 LIKE ''%' + @零件名称 + '%'' '
    
    -- 日期范围过滤（如果提供了日期参数）
    IF @开始日期 IS NOT NULL
        SET @where = @where + ' AND 检测时间 >= ''' + CONVERT(nvarchar(30), @开始日期, 120) + ''' '
    
    IF @结束日期 IS NOT NULL
        SET @where = @where + ' AND 检测时间 <= ''' + CONVERT(nvarchar(30), @结束日期, 120) + ''' '
	 SET @selStr = @selStr + @where + ' ORDER BY 检测时间 desc'
	print @selStr
	 EXEC sp_executesql @selStr
END
GO
/****** Object:  StoredProcedure [dbo].[质量管理_质量检验_入库质检任务_查询]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[质量管理_质量检验_入库质检任务_查询]
    @订单号 NVARCHAR(100) = '',
    @零件编号 NVARCHAR(100) = '',
    @零件名称 NVARCHAR(100) = '',
    @检测日期_Start NVARCHAR(20) = '',
    @检测日期_End NVARCHAR(20) = '',
    @检测结果 NVARCHAR(10) = '',
    @检测人 NVARCHAR(50) = '',
	@状态 NVARCHAR(10) = '',
	@单据码 NVARCHAR(50) = ''
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @SQL NVARCHAR(MAX)
    DECLARE @WhereConditions NVARCHAR(MAX) = ''
    DECLARE @TaskWhere NVARCHAR(MAX) = ''
    DECLARE @OuterWhere NVARCHAR(MAX) = ''

    -- 构建任务表筛选条件（用于内层）
	SET @TaskWhere = @TaskWhere + ' AND (task.订单类型 = ''20'') '
	IF @单据码 <> ''
        SET @TaskWhere = @TaskWhere + ' AND task.单据码 LIKE ''%' + @单据码 + '%'''
    IF @订单号 <> ''
        SET @TaskWhere = @TaskWhere + ' AND task.订单编号 LIKE ''%' + @订单号 + '%'''
    IF @零件编号 <> ''
        SET @TaskWhere = @TaskWhere + ' AND task.物料编码 LIKE ''%' + @零件编号 + '%'''
    IF @零件名称 <> ''
        SET @TaskWhere = @TaskWhere + ' AND task.物料名称 LIKE ''%' + @零件名称 + '%'''

    -- 构建外层筛选条件（用于计算结果）
    IF @检测结果 <> ''
        SET @OuterWhere = @OuterWhere + ' AND 检测结果 = ' + @检测结果
    IF @状态 <> ''
        SET @OuterWhere = @OuterWhere + ' AND 状态 = ''' + @状态 + ''''
    IF @检测人 <> ''
        SET @OuterWhere = @OuterWhere + ' AND 检测人 LIKE ''%' + @检测人 + '%'''
    IF @检测日期_Start <> '' AND @检测日期_End <> ''
        SET @OuterWhere = @OuterWhere + ' AND CAST(检验时间 AS DATE) BETWEEN ''' + @检测日期_Start + ''' AND ''' + @检测日期_End + ''''

    -- 构建内层WHERE
    DECLARE @InnerWhere NVARCHAR(MAX) = ''
    IF LEN(@TaskWhere) > 0
        SET @InnerWhere = ' WHERE ' + SUBSTRING(@TaskWhere, 5, LEN(@TaskWhere))

	SET @SQL = '
WITH QualityData AS (
    -- 只取类型6的数据用于统计（避免重复）
    SELECT 
        计划号, 
        检验数量, 
        合格数, 
        不合格数, 
        检测人, 
        检测时间,
        6 AS 检测类型编号
    FROM [dbo].[YL_质量检验_质检记录]
    WHERE 检测类型编号 = 5
),
-- 统计已检验数量和合格数（只统计原始记录）
CheckedQuantity AS (
    SELECT 
        计划号,
        行号,
        订单类型 AS 质检订单类型,
        SUM(检验数量) AS 已检验数量,
        SUM(合格数) AS 累计合格数,
        SUM(不合格数) AS 累计不合格数
    FROM [dbo].[YL_质量检验_质检记录]
    WHERE 检测类型编号 = 5
    GROUP BY 计划号, 行号, 订单类型
),
AggregatedData AS (
    SELECT 
        task.订单编号 AS 计划号,
        task.单据码,
        task.订单类型,
        task.物料编码,
        task.物料名称,
        task.到货数,
        task.入库数量,
        task.加急状态,
        task.行号,
        task.采购到货时间,
        task.存放位置,
        task.加急总数,
        -- 使用累计数据
        ISNULL(cq.已检验数量, 0) AS 检验数量,
        ISNULL(cq.累计合格数, 0) AS 合格数,
        ISNULL(cq.累计不合格数, 0) AS 不合格数,
        ISNULL(cq.已检验数量, 0) AS 已检验数量,
        task.入库数量 - ISNULL(cq.已检验数量, 0) AS 剩余待检数量,
        -- 检测人（取最新的或合并多人）
        CASE 
            WHEN COUNT(DISTINCT qd.检测人) = 1 THEN MAX(qd.检测人)
            ELSE STUFF((
                SELECT DISTINCT '', '' + 检测人 
                FROM QualityData qd2 
                WHERE qd2.计划号 = task.订单编号
                  AND ISNULL(qd2.检测人, '''') <> ''''
                FOR XML PATH('''')), 1, 2, '''')
        END AS 检测人,
        MAX(qd.检测时间) AS 检验时间,
        -- 检测结果（基于累计数据）
        CASE 
            WHEN ISNULL(cq.累计不合格数, 0) > 0 THEN 2  -- 有不合格记录
            WHEN ISNULL(cq.累计合格数, 0) > 0 THEN 1  -- 有合格记录且无不合格
            ELSE 0  -- 无检验记录
        END AS 检测结果,
        -- 检验状态（基于累计检验数量与到货数量对比）
        CASE 
            WHEN ISNULL(cq.已检验数量, 0) >= task.入库数量 AND task.入库数量 > 0 THEN ''1''  -- 已完成
            ELSE ''0''  -- 未完成
        END AS 状态
    FROM [dbo].[质量检验_质检任务_SAP] task
    LEFT JOIN QualityData qd ON task.订单编号 = qd.计划号
    LEFT JOIN CheckedQuantity cq ON task.订单编号 = cq.计划号 AND task.行号 = cq.行号 AND task.订单类型 = cq.质检订单类型
    ' + @InnerWhere + '
    GROUP BY task.订单编号, task.单据码, task.订单类型, task.物料编码, task.物料名称, task.到货数, task.入库数量, task.加急状态, task.行号, task.采购到货时间, task.存放位置, task.加急总数, cq.已检验数量, cq.累计合格数, cq.累计不合格数
)
SELECT * FROM AggregatedData
WHERE 1=1' + @OuterWhere + '
ORDER BY 加急状态 DESC'

    -- 打印SQL语句用于调试
    PRINT @SQL
    
    -- 执行动态SQL
    EXEC sp_executesql @SQL
END
GO
/****** Object:  StoredProcedure [dbo].[质量管理_质量检验_收检记录_查询]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[质量管理_质量检验_收检记录_查询]
    @合同号 NVARCHAR(100) = '',
    @订单号 NVARCHAR(100) = '',
    @零件编号 NVARCHAR(100) = '',
    @零件名称 NVARCHAR(100) = '',
    @完工日期_Start NVARCHAR(20) = '',
    @完工日期_End NVARCHAR(20) = '',
    @检测日期_Start NVARCHAR(20) = '',
    @检测日期_End NVARCHAR(20) = '',
    @检测结果 NVARCHAR(10) = '',
    @检测人 NVARCHAR(50) = '',
    @检测类别 NVARCHAR(50) = '',
	@检测状态 NVARCHAR(50) = '',
	@属性 NVARCHAR(50) = ''
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @SQL NVARCHAR(MAX)
    DECLARE @WhereConditions NVARCHAR(MAX) = ' and v.单据状态 is null '

    -- 构建WHERE条件

    IF @订单号 <> ''
        SET @WhereConditions = @WhereConditions + ' AND o.订单编号 =  '+ @订单号 +''
	IF (@合同号 <> '')
        SET @WhereConditions = @WhereConditions + ' AND v.[合同号] LIKE ''%' + @合同号 + '%'''

    IF @零件编号 <> ''
        SET @WhereConditions = @WhereConditions + ' AND o.物料编号 LIKE ''%' + @零件编号 + '%'''

    IF @零件名称 <> ''
        SET @WhereConditions = @WhereConditions + ' AND o.物料描述 LIKE ''%' + @零件名称 + '%'''


    ---- 检测日期范围
    --IF @检测日期_Start <> '' AND @检测日期_End <> ''
    --    SET @WhereConditions = @WhereConditions + ' AND CONVERT(DATE, ISNULL(q.检测时间, 0)) BETWEEN ''' + @检测日期_Start + ''' AND ''' + @检测日期_End + ''''

    ---- 检测结果处理（需要根据合格数和不合格数判断）
    IF @检测结果 <> ''
    BEGIN
        IF @检测结果 = '1'  -- 合格
            SET @WhereConditions = @WhereConditions + ' AND (q.合格数 > 0 AND q.不合格数 = 0)'
        ELSE IF @检测结果 = '0'  -- 不合格
            SET @WhereConditions = @WhereConditions + ' AND (q.不合格数 > 0)'
    END
	IF @检测状态 = 1
		SET @WhereConditions = @WhereConditions + ' AND (ISNULL(q.检验数量,0)) = (ISNULL(o.完成数量,0))'
	IF @检测状态 = 0
		SET @WhereConditions = @WhereConditions + ' AND (ISNULL(q.检验数量,0)) < (ISNULL(o.完成数量,0))'
	IF @检测状态 = 2
		SET @WhereConditions = @WhereConditions 
	IF @属性 = 1
		SET @WhereConditions = @WhereConditions + ' AND 自制件属性 NOT LIKE ''%装配%'''
	IF @属性 = 2
		SET @WhereConditions = @WhereConditions + ' AND 自制件属性 LIKE ''%装配%'''
	IF @属性 = 0
		SET @WhereConditions = @WhereConditions 
    IF @检测人 <> ''
        SET @WhereConditions = @WhereConditions + ' AND ISNULL(q.检测人, '''') LIKE ''%' + @检测人 + '%'''

    --SET @WhereConditions = @WhereConditions + ' AND ISNULL(q.检测类型编号, 0) = ''6'''
	--SET @WhereConditions = @WhereConditions + ' AND ISNULL(o.操作类别编号, 0) = ''6'''
    -- 移除开头的" AND "
    IF LEN(@WhereConditions) > 0
        SET @WhereConditions = ' WHERE ' + SUBSTRING(@WhereConditions, 5, LEN(@WhereConditions))

	SET @SQL = '
	WITH QualitySummary AS (
    SELECT 
        TaskAID,
        SUM(检验数量) AS 检验数量,
        SUM(合格数) AS 合格数,
        SUM(不合格数) AS 不合格数,
        MAX(检测人) AS 检测人,
        MAX(检测时间) AS 检测时间,
        MAX(检测说明) AS 检测说明
    FROM [dbo].[YL_质量检验_质检记录]
    WHERE 检测类型编号 = 6
    GROUP BY TaskAID
),
OperationSummary AS (
    SELECT 
        TaskAID,
        订单编号,
        物料描述,
        物料编号,
        --工位名称,
        工序名称,
        SUM(ISNULL(操作数值, 0)) AS 完成数量
    FROM [dbo].[YL_加工中心_操作记录表]
    WHERE ISNULL(操作类别编号, 0) in (3,6)
    GROUP BY 
        TaskAID,
        订单编号,
        物料描述,
        物料编号,
        --工位名称,
        工序名称
)
SELECT top 100
    o.TaskAID AS TaskAID,
    o.订单编号 AS 计划号,
	v.合同号,
    o.物料描述 AS 零件名称,
    o.物料编号 AS 零件编码,
    --o.工位名称 AS 工位名称,
	v.指派对象 as 工位名称,
    o.工序名称 AS 工序名称,
	自制件属性 ,
    o.完成数量 AS 完成数量,
	v.加急状态 AS 加急状态,
	v.加急总数 AS 加急总数,
    ISNULL(q.检验数量, 0) AS 检验数量,
    ISNULL(q.合格数, 0) AS 合格数,
    ISNULL(q.不合格数, 0) AS 不合格数,
    ISNULL(q.检测人, '''') AS 检测人,
    ISNULL(CONVERT(NVARCHAR(19), q.检测时间, 120), '''') AS 检测时间,
    ISNULL(q.检测说明, '''') AS 检测说明,
    CASE 
        WHEN q.TaskAID IS NULL THEN 0
        WHEN q.合格数 > 0 AND q.不合格数 = 0 THEN 1
        WHEN q.不合格数 > 0 THEN 2
        ELSE 0
    END AS 检测状态
FROM OperationSummary AS o
LEFT JOIN QualitySummary AS q ON o.TaskAID = q.TaskAID
LEFT JOIN [dbo].[View_生产订单_MES] as v ON o.TaskAID = v.TaskAID
' + @WhereConditions + '

 ORDER BY o.订单编号 desc'

    -- 打印SQL语句用于调试
    PRINT @SQL
    
    -- 执行动态SQL
    EXEC sp_executesql @SQL
END
GO
/****** Object:  StoredProcedure [dbo].[质量管理_质量检验_退货质检任务_查询]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[质量管理_质量检验_退货质检任务_查询]
    @订单号 NVARCHAR(100) = '',
    @零件编号 NVARCHAR(100) = '',
    @零件名称 NVARCHAR(100) = '',
    @检测日期_Start NVARCHAR(20) = '',
    @检测日期_End NVARCHAR(20) = '',
    @检测结果 NVARCHAR(10) = '',
    @检测人 NVARCHAR(50) = ''
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @SQL NVARCHAR(MAX)
    DECLARE @WhereConditions NVARCHAR(MAX) = ''

    -- 构建WHERE条件

	SET @WhereConditions = @WhereConditions + ' AND (订单类型 = ''234000031'') '
    IF @订单号 <> ''
        SET @WhereConditions = @WhereConditions + ' AND 订单编号 LIKE ''%' + @订单号 + '%'''

    IF @零件编号 <> ''
        SET @WhereConditions = @WhereConditions + ' AND 物料编码 LIKE ''%' + @零件编号 + '%'''

    IF @零件名称 <> ''
        SET @WhereConditions = @WhereConditions + ' AND 物料名称 LIKE ''%' + @零件名称 + '%'''


    -- 检测日期范围
    IF @检测日期_Start <> '' AND @检测日期_End <> ''
        SET @WhereConditions = @WhereConditions + ' AND CONVERT(DATE, 检验时间) BETWEEN ''' + @检测日期_Start + ''' AND ''' + @检测日期_End + ''''

    -- 检测结果处理（需要根据合格数和不合格数判断）
    IF @检测结果 <> ''
    BEGIN
        IF @检测结果 = '1'  -- 合格
            SET @WhereConditions = @WhereConditions + ' AND (合格数 > 0 AND 不合格数 = 0)'
        ELSE IF @检测结果 = '0'  -- 不合格
            SET @WhereConditions = @WhereConditions + ' AND ( 不合格数 > 0)'
    END

    IF @检测人 <> ''
        SET @WhereConditions = @WhereConditions + ' AND ISNULL( 检测人, '''') LIKE ''%' + @检测人 + '%'''


    -- 移除开头的" AND "
    IF LEN(@WhereConditions) > 0
        SET @WhereConditions = ' WHERE ' + SUBSTRING(@WhereConditions, 5, LEN(@WhereConditions))

	SET @SQL = '
	SELECT 
		* from [dbo].[质量检验_质检任务_SAP] '+@WhereConditions+'' 

    -- 打印SQL语句用于调试
    PRINT @SQL
    
    -- 执行动态SQL
    EXEC sp_executesql @SQL
END
GO
/****** Object:  StoredProcedure [dbo].[质量管理_质量检验_终检记录_查询]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[质量管理_质量检验_终检记录_查询]
    @合同号 NVARCHAR(100) = '',
    @订单号 NVARCHAR(100) = '',
    @零件编号 NVARCHAR(100) = '',
    @零件名称 NVARCHAR(100) = '',
    @检测日期_Start NVARCHAR(20) = '',
    @检测日期_End NVARCHAR(20) = '',
    @检测结果 NVARCHAR(10) = '',
    @检测人 NVARCHAR(50) = ''
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @SQL NVARCHAR(MAX)
    DECLARE @WhereConditions NVARCHAR(MAX) = ''

    -- 构建WHERE条件
    IF @合同号 <> ''
        SET @WhereConditions = @WhereConditions + ' AND 内部合同号 LIKE ''%' + @合同号 + '%'''

    IF @订单号 <> ''
        SET @WhereConditions = @WhereConditions + ' AND 计划号 LIKE ''%' + @订单号 + '%'''

    IF @零件编号 <> ''
        SET @WhereConditions = @WhereConditions + ' AND 零件编码 LIKE ''%' + @零件编号 + '%'''

    IF @零件名称 <> ''
        SET @WhereConditions = @WhereConditions + ' AND 零件名称 LIKE ''%' + @零件名称 + '%'''

    -- 检测日期范围
    IF @检测日期_Start <> '' AND @检测日期_End <> ''
        SET @WhereConditions = @WhereConditions + ' AND CONVERT(DATE, 检测时间) BETWEEN ''' + @检测日期_Start + ''' AND ''' + @检测日期_End + ''''

    -- 检测结果处理
    IF @检测结果 <> ''
    BEGIN
        IF @检测结果 = '1'  -- 合格
            SET @WhereConditions = @WhereConditions + ' AND (合格数 > 0 AND 不合格数 = 0)'
        ELSE IF @检测结果 = '0'  -- 不合格
            SET @WhereConditions = @WhereConditions + ' AND (不合格数 > 0)'
    END

    IF @检测人 <> ''
        SET @WhereConditions = @WhereConditions + ' AND 检测人 LIKE ''%' + @检测人 + '%'''

    -- 只查询终检类型的记录
    SET @WhereConditions = @WhereConditions + ' AND 质检类型 = ''终检'' AND 检测类型编号 = 8'

    -- 移除开头的" AND "
    IF LEN(@WhereConditions) > 0
        SET @WhereConditions = ' WHERE ' + SUBSTRING(@WhereConditions, 5, LEN(@WhereConditions))

    SET @SQL = '
    SELECT 
        QT_AID,
        TaskAID,
        检测类型编号,
        质检类型,
        零件编码,
        零件名称,
        内部合同号,
        计划号,
        工序名称,
        计划生产数,
        检验数量,
        合格数,
        不合格数,
        检测人,
        CONVERT(NVARCHAR(19), 检测时间, 120) AS 检测时间,
        检测说明
    FROM [dbo].[YL_质量检验_质检记录]
    ' + @WhereConditions + '
    ORDER BY 检测时间 DESC, 内部合同号, 计划号'

    -- 打印SQL语句用于调试
    PRINT @SQL
    
    -- 执行动态SQL
    EXEC sp_executesql @SQL
END
GO
/****** Object:  StoredProcedure [dbo].[质量管理_质量检验_终检数据_查询]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[质量管理_质量检验_终检数据_查询]
    @合同号 NVARCHAR(100) = '',
    @订单号 NVARCHAR(100) = '',
    @零件编号 NVARCHAR(100) = '',
    @零件名称 NVARCHAR(100) = '',
    @完工日期_Start NVARCHAR(20) = '',
    @完工日期_End NVARCHAR(20) = '',
    @检测日期_Start NVARCHAR(20) = '',
    @检测日期_End NVARCHAR(20) = '',
    @检测结果 NVARCHAR(10) = '',
    @检测人 NVARCHAR(50) = '',
    @检测类别 NVARCHAR(50) = '',
    @检验状态 NVARCHAR(10) = '',  -- 新增：检验状态筛选（1:已完成, 0:未完成）
	@属性 NVARCHAR(50) = ''
	
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @SQL NVARCHAR(MAX)
    DECLARE @WhereConditions NVARCHAR(MAX) = ''

    -- 构建WHERE条件
    IF @合同号 <> ''
        SET @WhereConditions = @WhereConditions + ' AND 内部合同号 LIKE ''%' + REPLACE(@合同号, '''', '''''') + '%'''

    IF @订单号 <> ''
        SET @WhereConditions = @WhereConditions + ' AND 计划号 = '+@订单号+''

    IF @零件编号 <> ''
        SET @WhereConditions = @WhereConditions + ' AND 零件编码 LIKE ''%' + REPLACE(@零件编号, '''', '''''') + '%'''

    IF @零件名称 <> ''
        SET @WhereConditions = @WhereConditions + ' AND 零件名称 LIKE ''%' + REPLACE(@零件名称, '''', '''''') + '%'''

    IF @完工日期_Start <> '' AND @完工日期_End <> ''
        SET @WhereConditions = @WhereConditions + ' AND CONVERT(DATE, 计划完成时间) BETWEEN ''' + @完工日期_Start + ''' AND ''' + @完工日期_End + ''''

    IF @检测日期_Start <> '' AND @检测日期_End <> ''
        SET @WhereConditions = @WhereConditions + ' AND CONVERT(DATE, 检测时间) BETWEEN ''' + @检测日期_Start + ''' AND ''' + @检测日期_End + ''''

    IF @检测结果 <> ''
    BEGIN
        IF @检测结果 = '1'
            SET @WhereConditions = @WhereConditions + ' AND 检测状态 = 1'  -- 合格
        ELSE IF @检测结果 = '0'
            SET @WhereConditions = @WhereConditions + ' AND 检测状态 = 2'  -- 不合格
    END

    IF @检测人 <> ''
        SET @WhereConditions = @WhereConditions + ' AND 检测人 LIKE ''%' + REPLACE(@检测人, '''', '''''') + '%'''

    IF @检测类别 <> ''
        SET @WhereConditions = @WhereConditions + ' AND 检测类别 = ''' + REPLACE(@检测类别, '''', '''''') + ''''

    IF @检验状态 <> ''
    BEGIN
        IF @检验状态 = '1'
            SET @WhereConditions = @WhereConditions + ' AND 检验状态 = ''已完成'''
        ELSE IF @检验状态 = '0'
            SET @WhereConditions = @WhereConditions + ' AND 检验状态 = ''未完成'''
    END
	IF @属性 = 1
		SET @WhereConditions = @WhereConditions + ' AND 自制件属性 NOT LIKE ''%装配%'''
	IF @属性 = 2
		SET @WhereConditions = @WhereConditions + ' AND 自制件属性 LIKE ''%装配%'''
	IF @属性 = 0
		SET @WhereConditions = @WhereConditions 

    -- 移除开头 AND 并添加 WHERE
    IF LEN(@WhereConditions) > 0
        SET @WhereConditions = ' WHERE 1=1 ' + SUBSTRING(@WhereConditions, 1, LEN(@WhereConditions))
    ELSE
        SET @WhereConditions = ''

    SET @SQL = '
       WITH LastProcessTasks AS (
            SELECT 订单编号, MAX(订单行号) AS 最大订单行号
            FROM [dbo].[MES_接口_生产计划_生产任务]
            GROUP BY 订单编号
        ),
        QualityData AS (
            -- 检测类型编号=6的数据（原始逻辑）
            SELECT 
                计划号, 
                检验数量, 
                合格数, 
                不合格数, 
                检测人, 
                检测时间,
                工序名称,
                TaskAID,
                6 AS 检测类型编号
            FROM [dbo].[YL_质量检验_质检记录]
            WHERE 检测类型编号 = 6
            
            UNION ALL
            
            -- 检测类型编号=8的数据（新逻辑：不合格数>0就是不合格）
            SELECT 
                计划号, 
                检验数量, 
                合格数, 
                不合格数, 
                检测人, 
                检测时间,
                工序名称,
                TaskAID,
                8 AS 检测类型编号
            FROM [dbo].[YL_质量检验_质检记录]
            WHERE 检测类型编号 = 8
        ),
        QualityDataByType AS (
            -- 按检测类型分别统计数量和
            SELECT 
                TaskAID,
                工序名称,
                sum(CASE WHEN 检测类型编号 = 6 THEN 检验数量 ELSE 0 END) AS 检验数量_6,
                sum(CASE WHEN 检测类型编号 = 8 THEN 检验数量 ELSE 0 END) AS 检验数量_8
            FROM QualityData
            GROUP BY TaskAID, 工序名称
        ),
        BaseData AS (
            SELECT 
			DISTINCT
                a.合同号 AS 内部合同号,
                a.订单编号 AS 计划号,
				b.加急总数,
                b.物料名称 AS 零件名称,
                b.物料编码 AS 零件编码,
                b.工序名称 AS 工序名称,
                b.指派数量 AS 计划生产数,
				b.加急状态 AS 加急状态,
                ISNULL(q.检验数量, 0) AS 检验数量,
                b.计划完成时间 AS 计划完成时间,
                ISNULL(q.合格数, 0) AS 合格数,
                ISNULL(q.不合格数, 0) AS 不合格数,
                q.检测人 AS 检测人,
                q.检测时间 AS 检测时间_raw,
                ISNULL(CONVERT(NVARCHAR(19), q.检测时间, 120), '''') AS 检测时间,
                q.检测类型编号 AS 检测类别,
				q.TaskAID,
                -- 计算检验状态
                CASE 
                    WHEN qt.检验数量_8 > 0 AND qt.检验数量_6 > 0 AND qt.检验数量_8 >= qt.检验数量_6 THEN ''已完成''
                    WHEN qt.检验数量_8 > 0 AND qt.检验数量_6 > 0 AND qt.检验数量_8 < qt.检验数量_6 THEN ''未完成''
                    WHEN qt.检验数量_8 = 0 AND qt.检验数量_6 > 0 THEN ''未完成''
                    WHEN qt.检验数量_8 > 0 AND qt.检验数量_6 = 0 THEN ''已完成''  -- 只有类型8的检验也算完成
                    ELSE ''未完成''
                END AS 检验状态,
                qt.检验数量_6,
                qt.检验数量_8,
				b.自制件属性 as 自制件属性
            FROM [YL_MESDB].[dbo].[YL_加工中心_操作记录表] AS a
            INNER JOIN [dbo].[View_生产订单_MES] AS b ON a.TaskAID = b.TaskAID
            INNER JOIN LastProcessTasks lpt ON a.订单编号 = lpt.订单编号 AND b.订单行号 = lpt.最大订单行号
            LEFT JOIN QualityData AS q ON b.TaskAID = q.TaskAID 
            LEFT JOIN QualityDataByType qt ON b.TaskAID = qt.TaskAID AND b.工序名称 = qt.工序名称
            where a.操作类别 in (''报工'',''辅助结束'') and b.单据状态 is null
        ),
        AggregatedData AS (
            SELECT 
			TaskAID,
                内部合同号,
				加急总数,
                计划号,
                零件名称,
                零件编码,
                工序名称,
				加急状态,
                SUM(检验数量) AS 检验数量,
                MAX(计划完成时间) AS 计划完成时间,
                SUM(合格数) AS 合格数,
                SUM(不合格数) AS 不合格数,
                CASE 
                    WHEN COUNT(DISTINCT 检测人) = 1 THEN MAX(检测人)
                    ELSE STUFF((
                        SELECT DISTINCT '', '' + 检测人 
                        FROM BaseData bd2 
                        WHERE bd2.计划号 = bd1.计划号 AND bd2.零件编码 = bd1.零件编码
                          AND ISNULL(bd2.检测人, '''') <> ''''
                        FOR XML PATH('''')), 1, 2, '''')
                END AS 检测人,
                MAX(检测时间) AS 检测时间,
                MAX(检测类别) AS 检测类别,
                -- 根据检测类型计算检测状态
                CASE 
                    WHEN MAX(检测类别) = 8 THEN
                        CASE WHEN SUM(不合格数) > 0 THEN 2 ELSE 1 END  -- 类型8：不合格数>0就不合格，否则合格
                    ELSE
                        CASE 
                            WHEN SUM(合格数) > 0 AND SUM(不合格数) = 0 THEN 1  -- 类型6：有合格数且无不合格数
                            WHEN SUM(不合格数) > 0 THEN 2  -- 类型6：有不合格数
                            ELSE 0
                        END
                END AS 检测状态,
                -- 检验状态（已完成/未完成）
                MAX(检验状态) AS 检验状态,
                MAX(检验数量_6) AS 检验数量_6,
                MAX(检验数量_8) AS 检验数量_8,
				自制件属性
            FROM BaseData bd1 where 检测类别 <> 8
            GROUP BY 内部合同号, 计划号, 零件编码, 零件名称, 工序名称,TaskAID,加急状态,加急总数,自制件属性
        )
        SELECT 
			TaskAID,
            内部合同号,
            计划号,
            零件名称,
            零件编码,
            工序名称,
            检验数量,
            计划完成时间,
            合格数,
            不合格数,
            检测人,
            检测时间,
            检测状态,
            检测类别,
            检验状态,  -- 新增：检验状态字段
			检验数量_6,
			检验数量_8,
			加急状态,
			加急总数,
			自制件属性
        FROM AggregatedData'

    -- 添加WHERE条件和ORDER BY
    IF LEN(@WhereConditions) > 0
        SET @SQL = @SQL + @WhereConditions
    
    SET @SQL = @SQL + ' ORDER BY 检测时间 DESC, 内部合同号, 计划号'

    PRINT @SQL  -- 调试用
    EXEC sp_executesql @SQL
END
GO
/****** Object:  StoredProcedure [dbo].[质量任务看板_当天已完成汇总]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [dbo].[质量任务看板_当天已完成汇总]
AS
BEGIN
    SET NOCOUNT ON;

    SELECT 
        COUNT(DISTINCT TaskAID) AS totalCount,
        isnull(SUM(合格数),0) AS passCount,
        isnull(SUM(不合格数),0) AS failCount
    FROM [YL_MESDB].[dbo].[View_质量检验_质检记录] 
    WHERE CAST(检测时间 AS DATE) = CAST(GETDATE() AS DATE)
END
GO
/****** Object:  StoredProcedure [dbo].[质量任务看板_当天已完成明细]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [dbo].[质量任务看板_当天已完成明细]

AS
BEGIN
    SET NOCOUNT ON;

	   -- ==================== 当天检测明细（含加急数量） ====================
	;WITH TodayQuality AS (
		SELECT 
			CASE 
				WHEN q.检测类型编号 = 5 THEN N'采购入库检'
				WHEN q.检测类型编号 = 6 AND q.质检类型 = N'工序检验' THEN N'序检收检'
				WHEN q.检测类型编号 = 8 THEN N'终检'
				WHEN q.订单类型 = '20' THEN N'采购入库检'
				WHEN q.订单类型 = '59' THEN N'其他入库检'
				WHEN q.订单类型 = '202-60' THEN N'原料退库检'
				WHEN q.订单类型 = '234000031' THEN N'销售退货检'
				ELSE q.质检类型
			END AS taskType,
			q.计划号 AS orderNo,
			q.零件名称 AS materialName,
			q.零件编码 AS materialCode,
			ISNULL(q.工序名称, N'') AS processName,
			SUM(q.检验数量) AS inspectQty,
			SUM(q.合格数) AS passQty,
			SUM(q.不合格数) AS failQty,
			q.TaskAID
		FROM [YL_MESDB].[dbo].[View_质量检验_质检记录] q
		WHERE CAST(q.检测时间 AS DATE) = CAST(GETDATE() AS DATE)
		GROUP BY 
			q.检测类型编号,
			q.质检类型,
			q.订单类型,
			q.计划号,
			q.零件名称,
			q.零件编码,
			q.工序名称,
			q.TaskAID
	)
	SELECT 
		t.taskType,
		t.orderNo,
		t.materialName,
		t.materialCode,
		t.processName,
		t.inspectQty,
		t.passQty,
		t.failQty,
		CASE WHEN ISNULL(v.加急状态, 0) > 0 THEN 
			t.inspectQty  -- 或者其他逻辑计算加急未完成数量
		ELSE 0 END AS urgentQty
	FROM TodayQuality t
	LEFT JOIN [dbo].[View_生产订单_MES] v ON t.TaskAID = v.TaskAID
	ORDER BY t.taskType, t.orderNo
END

GO
/****** Object:  StoredProcedure [dbo].[质量任务看板_未完成明细查询]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[质量任务看板_未完成明细查询]
AS
BEGIN
    SET NOCOUNT ON;

    -- 创建临时表存储结果
    CREATE TABLE #TempResult (
        taskType NVARCHAR(50),
        orderNo NVARCHAR(100),
        materialName NVARCHAR(200),
        materialCode NVARCHAR(100),
        processName NVARCHAR(100),
        inspectQty INT,
        passQty INT,
        failQty INT,
        urgentQty INT
    )

    -- ==================== 1. 收检记录（工序检验）未完成 ====================
    ;WITH QualitySummary AS (
        SELECT 
            TaskAID,
            SUM(检验数量) AS 检验数量,
            SUM(合格数) AS 合格数,
            SUM(不合格数) AS 不合格数
        FROM [dbo].[YL_质量检验_质检记录]
        WHERE 检测类型编号 = 6
        GROUP BY TaskAID
    ),
    OperationSummary AS (
        SELECT 
            TaskAID,
            订单编号,
            物料描述,
            物料编号,
            工序名称,
            SUM(ISNULL(操作数值, 0)) AS 完成数量
        FROM [dbo].[YL_加工中心_操作记录表]
        WHERE ISNULL(操作类别编号, 0) IN (3,6)
        GROUP BY TaskAID, 订单编号, 物料描述, 物料编号, 工序名称
    )
    INSERT INTO #TempResult
    SELECT 
        N'序检收检' AS taskType,
        o.订单编号 AS orderNo,
        o.物料描述 AS materialName,
        o.物料编号 AS materialCode,
        o.工序名称 AS processName,
        ISNULL(q.检验数量, 0) AS inspectQty,
        ISNULL(q.合格数, 0) AS passQty,
        ISNULL(q.不合格数, 0) AS failQty,
        CASE WHEN ISNULL(v.加急状态, 0) > 0 THEN 1 ELSE 0 END AS urgentQty
    FROM OperationSummary AS o
    LEFT JOIN QualitySummary AS q ON o.TaskAID = q.TaskAID
    LEFT JOIN [dbo].[View_生产订单_MES] AS v ON o.TaskAID = v.TaskAID
    WHERE v.单据状态 IS NULL
        AND (ISNULL(q.检验数量, 0)) < (ISNULL(o.完成数量, 0))

    -- ==================== 2. 其他入库质检 未完成 ====================
    INSERT INTO #TempResult
    SELECT 
        N'其他入库检' AS taskType,
        订单编号 AS orderNo,
        物料名称 AS materialName,
        物料编码 AS materialCode,
        N'' AS processName,
        ISNULL(合格数, 0) + ISNULL(不合格数, 0) AS inspectQty,
        ISNULL(合格数, 0) AS passQty,
        ISNULL(不合格数, 0) AS failQty,
        CASE WHEN ISNULL(加急状态, 0) > 0 THEN 1 ELSE 0 END AS urgentQty
    FROM [dbo].[质量检验_质检任务_SAP]
    WHERE 订单类型 = '59'
        AND (ISNULL(合格数, 0) + ISNULL(不合格数, 0) < ISNULL(到货数, 入库数量))

    -- ==================== 3. 原材料退库质检 未完成 ====================
    INSERT INTO #TempResult
    SELECT 
        N'原料退库检' AS taskType,
        订单编号 AS orderNo,
        物料名称 AS materialName,
        物料编码 AS materialCode,
        N'' AS processName,
        ISNULL(合格数, 0) + ISNULL(不合格数, 0) AS inspectQty,
        ISNULL(合格数, 0) AS passQty,
        ISNULL(不合格数, 0) AS failQty,
        CASE WHEN ISNULL(加急状态, 0) > 0 THEN 1 ELSE 0 END AS urgentQty
    FROM [dbo].[质量检验_质检任务_SAP]
    WHERE 订单类型 = '202-60'
        AND (ISNULL(合格数, 0) + ISNULL(不合格数, 0) < ISNULL(到货数, 入库数量))

    -- ==================== 4. 退货质检任务 未完成 ====================
    INSERT INTO #TempResult
    SELECT 
        N'销售退货检' AS taskType,
        订单编号 AS orderNo,
        物料名称 AS materialName,
        物料编码 AS materialCode,
        N'' AS processName,
        ISNULL(合格数, 0) + ISNULL(不合格数, 0) AS inspectQty,
        ISNULL(合格数, 0) AS passQty,
        ISNULL(不合格数, 0) AS failQty,
        CASE WHEN ISNULL(加急状态, 0) > 0 THEN 1 ELSE 0 END AS urgentQty
    FROM [dbo].[质量检验_质检任务_SAP]
    WHERE 订单类型 = '234000031'
        AND (ISNULL(合格数, 0) + ISNULL(不合格数, 0) < ISNULL(到货数, 0))

    -- ==================== 5. 入库质检任务 未完成 ====================
    ;WITH QualityData AS (
        SELECT 
            计划号,
            行号,
            订单类型 AS 质检订单类型,
            SUM(检验数量) AS 已检验数量,
            SUM(合格数) AS 合格数,
            SUM(不合格数) AS 不合格数
        FROM [dbo].[YL_质量检验_质检记录]
        WHERE 检测类型编号 = 5
        GROUP BY 计划号, 行号, 订单类型
    )
    INSERT INTO #TempResult
    SELECT 
        N'采购入库检' AS taskType,
        task.订单编号 AS orderNo,
        task.物料名称 AS materialName,
        task.物料编码 AS materialCode,
        N'' AS processName,
        ISNULL(cq.已检验数量, 0) AS inspectQty,
        ISNULL(cq.合格数, 0) AS passQty,
        ISNULL(cq.不合格数, 0) AS failQty,
        CASE WHEN ISNULL(task.加急状态, 0) > 0 THEN 1 ELSE 0 END AS urgentQty
    FROM [dbo].[质量检验_质检任务_SAP] task
    LEFT JOIN QualityData cq ON task.订单编号 = cq.计划号 
        AND task.行号 = cq.行号 
        AND task.订单类型 = cq.质检订单类型
    WHERE task.订单类型 = '20'
        AND (ISNULL(cq.已检验数量, 0) < task.入库数量)

    -- ==================== 6. 终检数据 未完成 ====================
    ;WITH LastProcessTasks AS (
        SELECT 订单编号, MAX(订单行号) AS 最大订单行号
        FROM [dbo].[MES_接口_生产计划_生产任务]
        GROUP BY 订单编号
    ),
    QualityData AS (
        SELECT 
            TaskAID,
            工序名称,
            SUM(CASE WHEN 检测类型编号 = 6 THEN 检验数量 ELSE 0 END) AS 检验数量_6,
            SUM(CASE WHEN 检测类型编号 = 8 THEN 检验数量 ELSE 0 END) AS 检验数量_8,
            SUM(CASE WHEN 检测类型编号 = 6 THEN 合格数 ELSE 0 END) AS 合格数_6,
            SUM(CASE WHEN 检测类型编号 = 8 THEN 合格数 ELSE 0 END) AS 合格数_8,
            SUM(CASE WHEN 检测类型编号 = 6 THEN 不合格数 ELSE 0 END) AS 不合格数_6,
            SUM(CASE WHEN 检测类型编号 = 8 THEN 不合格数 ELSE 0 END) AS 不合格数_8
        FROM [dbo].[YL_质量检验_质检记录]
        WHERE 检测类型编号 IN (6, 8)
        GROUP BY TaskAID, 工序名称
    )
    INSERT INTO #TempResult
    SELECT DISTINCT
        N'终检' AS taskType,
        b.订单编号 AS orderNo,
        b.物料名称 AS materialName,
        b.物料编码 AS materialCode,
        b.工序名称 AS processName,
        ISNULL(q.检验数量_6, 0) + ISNULL(q.检验数量_8, 0) AS inspectQty,
        ISNULL(q.合格数_6, 0) + ISNULL(q.合格数_8, 0) AS passQty,
        ISNULL(q.不合格数_6, 0) + ISNULL(q.不合格数_8, 0) AS failQty,
        CASE WHEN ISNULL(b.加急状态, 0) > 0 THEN 
            1
        ELSE 0 END AS urgentQty
    FROM [YL_MESDB].[dbo].[YL_加工中心_操作记录表] AS a
    INNER JOIN [dbo].[View_生产订单_MES] AS b ON a.TaskAID = b.TaskAID
    INNER JOIN LastProcessTasks lpt ON a.订单编号 = lpt.订单编号 AND b.订单行号 = lpt.最大订单行号
    LEFT JOIN QualityData AS q ON b.TaskAID = q.TaskAID AND b.工序名称 = q.工序名称
    WHERE a.操作类别 IN ('报工', '辅助结束') 
        AND b.单据状态 IS NULL
        AND (
            (q.检验数量_8 > 0 AND q.检验数量_6 > 0 AND q.检验数量_8 < q.检验数量_6)
            OR (q.检验数量_8 = 0 AND q.检验数量_6 > 0)
            OR (q.检验数量_6 = 0 AND q.检验数量_8 = 0)
        )

    -- ==================== 返回结果 ====================
    SELECT 
        taskType,
        orderNo,
        materialName,
        materialCode,
        processName,
        inspectQty,
        passQty,
        failQty,
        urgentQty,
        CASE WHEN urgentQty > 0 THEN N'加急' ELSE N'待检' END AS status
    FROM #TempResult
    ORDER BY 
        CASE WHEN urgentQty > 0 THEN 0 ELSE 1 END,  -- 加急优先排序
        taskType, 
        orderNo

    DROP TABLE #TempResult
END
GO
/****** Object:  StoredProcedure [dbo].[质量任务看板_未完成统计]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

create PROCEDURE [dbo].[质量任务看板_未完成统计]
AS
BEGIN
    SET NOCOUNT ON;

    -- 创建临时表存储结果
    CREATE TABLE #Result (
        质检类型 NVARCHAR(50),
        未完成数量 INT,
        加急数量 INT
    )

    -- ==================== 1. 收检记录（工序检验）未完成 ====================
    ;WITH QualitySummary AS (
        SELECT 
            TaskAID,
            SUM(检验数量) AS 检验数量
        FROM [dbo].[YL_质量检验_质检记录]
        WHERE 检测类型编号 = 6
        GROUP BY TaskAID
    ),
    OperationSummary AS (
        SELECT 
            TaskAID,
            SUM(ISNULL(操作数值, 0)) AS 完成数量
        FROM [dbo].[YL_加工中心_操作记录表]
        WHERE ISNULL(操作类别编号, 0) IN (3,6)
        GROUP BY TaskAID
    )
    INSERT INTO #Result
    SELECT 
        '收检记录(工序检验)' AS 质检类型, 
        COUNT(*) AS 未完成数量,
        SUM(CASE WHEN ISNULL(v.加急状态, 0) > 0 THEN 1 ELSE 0 END) AS 加急数量
    FROM OperationSummary AS o
    LEFT JOIN QualitySummary AS q ON o.TaskAID = q.TaskAID
    LEFT JOIN [dbo].[View_生产订单_MES] AS v ON o.TaskAID = v.TaskAID
    WHERE v.单据状态 IS NULL
        AND (ISNULL(q.检验数量, 0)) < (ISNULL(o.完成数量, 0))

    -- ==================== 2. 其他入库质检 未完成 ====================
    INSERT INTO #Result
    SELECT 
        '其他入库质检' AS 质检类型, 
        COUNT(*) AS 未完成数量,
        SUM(CASE WHEN ISNULL(加急状态, 0) > 0 THEN 1 ELSE 0 END) AS 加急数量
    FROM [dbo].[质量检验_质检任务_SAP]
    WHERE 订单类型 = '59'
        AND (ISNULL(合格数, 0) + ISNULL(不合格数, 0) < ISNULL(到货数, 入库数量))

    -- ==================== 3. 原材料退库质检 未完成 ====================
    INSERT INTO #Result
    SELECT 
        '原材料退库质检' AS 质检类型, 
        COUNT(*) AS 未完成数量,
        SUM(CASE WHEN ISNULL(加急状态, 0) > 0 THEN 1 ELSE 0 END) AS 加急数量
    FROM [dbo].[质量检验_质检任务_SAP]
    WHERE 订单类型 = '202-60'
        AND (ISNULL(合格数, 0) + ISNULL(不合格数, 0) < ISNULL(到货数, 入库数量))

    -- ==================== 4. 退货质检任务 未完成 ====================
    INSERT INTO #Result
    SELECT 
        '退货质检任务' AS 质检类型, 
        COUNT(*) AS 未完成数量,
        SUM(CASE WHEN ISNULL(加急状态, 0) > 0 THEN 1 ELSE 0 END) AS 加急数量
    FROM [dbo].[质量检验_质检任务_SAP]
    WHERE 订单类型 = '234000031'
        AND (ISNULL(合格数, 0) + ISNULL(不合格数, 0) < ISNULL(到货数, 0))

    -- ==================== 5. 入库质检任务 未完成 ====================
    ;WITH QualityData AS (
        SELECT 
            计划号,
            行号,
            订单类型 AS 质检订单类型,
            SUM(检验数量) AS 已检验数量
        FROM [dbo].[YL_质量检验_质检记录]
        WHERE 检测类型编号 = 5
        GROUP BY 计划号, 行号, 订单类型
    )
    INSERT INTO #Result
    SELECT 
        '入库质检任务' AS 质检类型, 
        COUNT(*) AS 未完成数量,
        SUM(CASE WHEN ISNULL(task.加急状态, 0) > 0 THEN 1 ELSE 0 END) AS 加急数量
    FROM [dbo].[质量检验_质检任务_SAP] task
    LEFT JOIN QualityData cq ON task.订单编号 = cq.计划号 
        AND task.行号 = cq.行号 
        AND task.订单类型 = cq.质检订单类型
    WHERE task.订单类型 = '20'
        AND (ISNULL(cq.已检验数量, 0) < task.入库数量)

    -- ==================== 6. 终检数据 未完成 ====================
    ;WITH LastProcessTasks AS (
        SELECT 订单编号, MAX(订单行号) AS 最大订单行号
        FROM [dbo].[MES_接口_生产计划_生产任务]
        GROUP BY 订单编号
    ),
    QualityData AS (
        SELECT 
            TaskAID,
            工序名称,
            SUM(CASE WHEN 检测类型编号 = 6 THEN 检验数量 ELSE 0 END) AS 检验数量_6,
            SUM(CASE WHEN 检测类型编号 = 8 THEN 检验数量 ELSE 0 END) AS 检验数量_8
        FROM [dbo].[YL_质量检验_质检记录]
        WHERE 检测类型编号 IN (6, 8)
        GROUP BY TaskAID, 工序名称
    ),
    UnfinishedTasks AS (
        SELECT DISTINCT
            b.TaskAID,
            b.加急状态
        FROM [YL_MESDB].[dbo].[YL_加工中心_操作记录表] AS a
        INNER JOIN [dbo].[View_生产订单_MES] AS b ON a.TaskAID = b.TaskAID
        INNER JOIN LastProcessTasks lpt ON a.订单编号 = lpt.订单编号 AND b.订单行号 = lpt.最大订单行号
        LEFT JOIN QualityData AS q ON b.TaskAID = q.TaskAID AND b.工序名称 = q.工序名称
        WHERE a.操作类别 IN ('报工', '辅助结束') 
            AND b.单据状态 IS NULL
            AND (
                (q.检验数量_8 > 0 AND q.检验数量_6 > 0 AND q.检验数量_8 < q.检验数量_6)
                OR (q.检验数量_8 = 0 AND q.检验数量_6 > 0)
                OR (q.检验数量_6 = 0 AND q.检验数量_8 = 0)
            )
    )
    INSERT INTO #Result
    SELECT 
        '终检数据' AS 质检类型, 
        COUNT(*) AS 未完成数量,
        SUM(CASE WHEN ISNULL(加急状态, 0) > 0 THEN 1 ELSE 0 END) AS 加急数量
    FROM UnfinishedTasks


        -- ==================== 输出结果（明细+汇总合并） ====================
    SELECT 
        质检类型,
        未完成数量,
        加急数量,
        CASE WHEN 质检类型 = '【汇总】' THEN 1 ELSE 0 END AS 排序字段
    FROM #Result 
    
    UNION ALL
    
    SELECT 
        '【汇总】' AS 质检类型,
        SUM(未完成数量) AS 未完成数量,
        SUM(加急数量) AS 加急数量,
        1 AS 排序字段
    FROM #Result
    
    ORDER BY 排序字段, 质检类型

    DROP TABLE #Result
END
GO
/****** Object:  StoredProcedure [dbo].[装配中心任务看板_加急任务总数查询]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[装配中心任务看板_加急任务总数查询]

AS
BEGIN
    DECLARE @whereStr nvarchar(max) = ' WHERE 排产状态 = 1 '
    DECLARE @selStr nvarchar(max) = 
    'SELECT 
		SUM(CASE WHEN 加急总数 > 0 THEN 1 ELSE 0 END) AS 加急总数
	FROM [View_生产订单_MES]'

    -- 基础过滤：排除外协
    SET @whereStr = @whereStr + ' AND [指派对象] <> ''外协'' AND [指派对象] LIKE ''%装配%'''



    -- 生产状态逻辑（核心修复点）
    BEGIN
        -- 未指定状态：只查 1（可执行）、2（已开工）
        SET @whereStr = @whereStr + ' AND ISNULL(任务状态, 0) IN (0,1,2) '

	END

    -- 拼接最终语句
    SET @selStr = @selStr + @whereStr

    -- 调试用（上线前可注释掉）
    PRINT @selStr

    EXEC sp_executesql @selStr
	
END
GO
/****** Object:  StoredProcedure [dbo].[装配中心任务看板_已完成任务]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[装配中心任务看板_已完成任务]
AS
BEGIN
    SET NOCOUNT ON;

    SELECT 

		  [零件编码]
		  ,[零件名称]
		  ,CAST(CASE WHEN [检验数量] > 0 
			   THEN [合格数] * 100.0 / [检验数量] 
			   ELSE 0 END AS DECIMAL(5,2)) AS [单项合格率],
		  计划号
    
	FROM [YL_MESDB].[dbo].[View_质量检验_质检记录] 
	WHERE 工序名称 = '装配' 
	  AND [检测时间] > GETDATE()-3
	ORDER BY [检测时间] DESC
END
GO
/****** Object:  StoredProcedure [dbo].[装配中心任务看板_异常未关闭总数]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

create PROCEDURE [dbo].[装配中心任务看板_异常未关闭总数]
AS
BEGIN
    SET NOCOUNT ON;

   SELECT count(*) as 装配异常未关闭总数
      
  FROM [YL_MESDB].[dbo].[YL_加工中心_操作记录表] 
  left join [dbo].[MES_接口_生产计划] on [dbo].[YL_加工中心_操作记录表] .订单编号 = [dbo].[MES_接口_生产计划] .订单编号
  WHERE CAST(开始时间 AS DATE) < CAST(GETDATE() AS DATE) 
  and 结束时间 is null 
  and 操作类别 = '开始加工'
  and 自制件属性 like '%装配%'
  and 开始时间 > '2026-03-12'
END
GO
/****** Object:  StoredProcedure [dbo].[装配中心任务看板_在制品缺件查询]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[装配中心任务看板_在制品缺件查询]
as
BEGIN
    SET NOCOUNT ON;
    
    BEGIN TRY
        -- 简化版本，只查询必要的字段
        SELECT
			t.订单编号,
            t.操作人 AS UserName,
            pt.发料状态,
			pt.齐套,
			pt.预计齐套时间
        FROM [dbo].[YL_加工中心_操作记录表] t
		LEFT JOIN [dbo].[MES_接口_生产计划] pt on pt.订单编号 = t.订单编号
        WHERE 
             t.操作类别 = '开始加工'
            AND t.结束时间 IS NULL
			and t.工位名称 like '%装配%'
			and t.操作数值 is not null
			and pt.发料状态 = 2
        ORDER BY t.开始时间 DESC;
        
        -- 返回状态信息
        SELECT '1' AS result, '查询成功' AS message;
        
    END TRY
    BEGIN CATCH
        DECLARE @ErrorMessage NVARCHAR(4000);
        SELECT @ErrorMessage = ERROR_MESSAGE();
        
        SELECT '0' AS result, '查询失败: ' + @ErrorMessage AS message;
        
        RAISERROR (@ErrorMessage, 16, 1);
    END CATCH
END
GO
/****** Object:  StoredProcedure [dbo].[装配中心任务看板_装配合格率]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[装配中心任务看板_装配合格率]
AS
BEGIN
    SET NOCOUNT ON;

    SELECT 
		  CAST(CASE WHEN SUM([检验数量]) > 0 
			   THEN SUM([合格数]) * 100.0 / SUM([检验数量]) 
			   ELSE 0 END AS DECIMAL(5,2)) AS [总合格率],
		  SUM([检验数量]) AS [总检验数量],
		  SUM([合格数]) AS [总合格数],
		  SUM([不合格数]) AS [总不合格数]
	FROM [YL_MESDB].[dbo].[View_质量检验_质检记录] 
	WHERE 工序名称 = '装配' 
	  AND [检测时间] > GETDATE()-3
END
GO
/****** Object:  StoredProcedure [dbo].[装配中心任务看板_装配任务查询]    Script Date: 2026/5/18 8:58:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[装配中心任务看板_装配任务查询]

AS
BEGIN
    DECLARE @whereStr nvarchar(max) = ' WHERE 排产状态 = 1 '
    DECLARE @selStr nvarchar(max) = 
    'SELECT TaskAID,
            [订单编号] as 订单号,
			合同号,
			自制件属性,
			isnull(加急总数,0) as 加急总数,
			派工特殊说明,
            [订单拆分内码],
            [订单行号],
            [开工时间],
            [物料编号] as 零件编码,
            [物料描述] as 零件名称,
            case when isnull([加急状态],0)=1 then ''加急'' else ''否'' end as [加急],
            [优先级] as [优先],
            [指派对象编号],
            [指派对象],
            [工序名称],
			[二次派工],
			[计划号],
            isnull([指派数量],0) as 分配数,
            [计划开始时间] as 计划开始,
            [计划完成时间] as 计划完成,
            [最晚开始时间] as 最晚开始,
            isnull([收料数量],0) as 收料,
            isnull([完成数量],0) as 完成数量,
			case 
                when isnull(齐套,0)=1 then ''是'' 
                when isnull(齐套,0)=0 then ''否''
			end as [齐套],
			case 
                when isnull(发料状态,0)=1 then ''发料齐套'' 
                when isnull(发料状态,0)=2 then ''发料缺件''
			end as [发料状态],
			case 
                when isnull(拣配状态,0)=1 then ''已拣配'' 
                when isnull(拣配状态,0)=0 then ''未拣配''
			end as [拣配状态],
            case 
                when isnull(任务状态,0)=4 then ''已完成'' 
                when isnull(任务状态,0)=2 then ''已开工'' 
                when isnull(任务状态,0)=0 then ''待执行'' 
                when isnull(任务状态,0)=1 then ''可执行''
                else '''' 
            end as [任务状态],
            case 
                when isnull(加工状态,0)=2 then ''辅助开始''
                when isnull(加工状态,0)=3 then ''辅助结束''
                when isnull(加工状态,0)=4 then ''开始加工''
                when isnull(加工状态,0)=5 then ''暂停''
                when isnull(加工状态,0)=6 then ''报工''
                else '''' 
            end as [加工状态] 
     FROM [View_生产订单_MES] AS main'
	BEGIN
        SET @whereStr = @whereStr + ' AND ISNULL(任务状态, 0) IN (0,1,2) '
    END
    -- 基础过滤：排除外协
    SET @whereStr = @whereStr + ' AND [指派对象] <> ''外协'' AND [指派对象] LIKE ''%装配%'''

    -- 订单号
    
    -- 生产状态逻辑（核心修复点）
   
    -- 拼接最终语句
    SET @selStr = @selStr + @whereStr + ' ORDER BY 加急总数 desc '

    -- 调试用（上线前可注释掉）
    PRINT @selStr

    EXEC sp_executesql @selStr
	
END
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'0不加急，1加急' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'MES_接口_生产计划', @level2type=N'COLUMN',@level2name=N'加急状态'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'0未排产，1已排产' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'MES_接口_生产计划', @level2type=N'COLUMN',@level2name=N'排产状态'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'0默认，1待执行，2已开工，4已完成' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'MES_接口_生产计划_生产任务', @level2type=N'COLUMN',@level2name=N'任务状态'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1开始加工、2休息、3辅助、4报工' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'MES_接口_生产计划_生产任务', @level2type=N'COLUMN',@level2name=N'加工状态'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPane1', @value=N'[0E232FF0-B466-11cf-A24F-00AA00A3EFFF, 1.00]
Begin DesignProperties = 
   Begin PaneConfigurations = 
      Begin PaneConfiguration = 0
         NumPanes = 4
         Configuration = "(H (1[40] 4[20] 2[20] 3) )"
      End
      Begin PaneConfiguration = 1
         NumPanes = 3
         Configuration = "(H (1 [50] 4 [25] 3))"
      End
      Begin PaneConfiguration = 2
         NumPanes = 3
         Configuration = "(H (1 [50] 2 [25] 3))"
      End
      Begin PaneConfiguration = 3
         NumPanes = 3
         Configuration = "(H (4 [30] 2 [40] 3))"
      End
      Begin PaneConfiguration = 4
         NumPanes = 2
         Configuration = "(H (1 [56] 3))"
      End
      Begin PaneConfiguration = 5
         NumPanes = 2
         Configuration = "(H (2 [66] 3))"
      End
      Begin PaneConfiguration = 6
         NumPanes = 2
         Configuration = "(H (4 [50] 3))"
      End
      Begin PaneConfiguration = 7
         NumPanes = 1
         Configuration = "(V (3))"
      End
      Begin PaneConfiguration = 8
         NumPanes = 3
         Configuration = "(H (1[56] 4[18] 2) )"
      End
      Begin PaneConfiguration = 9
         NumPanes = 2
         Configuration = "(H (1 [75] 4))"
      End
      Begin PaneConfiguration = 10
         NumPanes = 2
         Configuration = "(H (1[66] 2) )"
      End
      Begin PaneConfiguration = 11
         NumPanes = 2
         Configuration = "(H (4 [60] 2))"
      End
      Begin PaneConfiguration = 12
         NumPanes = 1
         Configuration = "(H (1) )"
      End
      Begin PaneConfiguration = 13
         NumPanes = 1
         Configuration = "(V (4))"
      End
      Begin PaneConfiguration = 14
         NumPanes = 1
         Configuration = "(V (2))"
      End
      ActivePaneConfig = 0
   End
   Begin DiagramPane = 
      Begin Origin = 
         Top = 0
         Left = 0
      End
      Begin Tables = 
         Begin Table = "YL_加工中心_操作记录表"
            Begin Extent = 
               Top = 9
               Left = 57
               Bottom = 201
               Right = 288
            End
            DisplayFlags = 280
            TopColumn = 5
         End
      End
   End
   Begin SQLPane = 
   End
   Begin DataPane = 
      Begin ParameterDefaults = ""
      End
      Begin ColumnWidths = 9
         Width = 284
         Width = 1000
         Width = 1000
         Width = 1000
         Width = 1000
         Width = 1000
         Width = 1000
         Width = 1000
         Width = 1000
      End
   End
   Begin CriteriaPane = 
      Begin ColumnWidths = 12
         Column = 1440
         Alias = 900
         Table = 1170
         Output = 720
         Append = 1400
         NewValue = 1170
         SortType = 1350
         SortOrder = 1410
         GroupBy = 1350
         Filter = 1350
         Or = 1350
         Or = 1350
         Or = 1350
      End
   End
End
' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'View_报工人员'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPaneCount', @value=1 , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'View_报工人员'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPane1', @value=N'[0E232FF0-B466-11cf-A24F-00AA00A3EFFF, 1.00]
Begin DesignProperties = 
   Begin PaneConfigurations = 
      Begin PaneConfiguration = 0
         NumPanes = 4
         Configuration = "(H (1[52] 4[24] 2[20] 3) )"
      End
      Begin PaneConfiguration = 1
         NumPanes = 3
         Configuration = "(H (1 [50] 4 [25] 3))"
      End
      Begin PaneConfiguration = 2
         NumPanes = 3
         Configuration = "(H (1 [50] 2 [25] 3))"
      End
      Begin PaneConfiguration = 3
         NumPanes = 3
         Configuration = "(H (4 [30] 2 [40] 3))"
      End
      Begin PaneConfiguration = 4
         NumPanes = 2
         Configuration = "(H (1 [56] 3))"
      End
      Begin PaneConfiguration = 5
         NumPanes = 2
         Configuration = "(H (2 [66] 3))"
      End
      Begin PaneConfiguration = 6
         NumPanes = 2
         Configuration = "(H (4 [50] 3))"
      End
      Begin PaneConfiguration = 7
         NumPanes = 1
         Configuration = "(V (3))"
      End
      Begin PaneConfiguration = 8
         NumPanes = 3
         Configuration = "(H (1[56] 4[18] 2) )"
      End
      Begin PaneConfiguration = 9
         NumPanes = 2
         Configuration = "(H (1 [75] 4))"
      End
      Begin PaneConfiguration = 10
         NumPanes = 2
         Configuration = "(H (1[66] 2) )"
      End
      Begin PaneConfiguration = 11
         NumPanes = 2
         Configuration = "(H (4 [60] 2))"
      End
      Begin PaneConfiguration = 12
         NumPanes = 1
         Configuration = "(H (1) )"
      End
      Begin PaneConfiguration = 13
         NumPanes = 1
         Configuration = "(V (4))"
      End
      Begin PaneConfiguration = 14
         NumPanes = 1
         Configuration = "(V (2))"
      End
      ActivePaneConfig = 0
   End
   Begin DiagramPane = 
      Begin Origin = 
         Top = 0
         Left = 0
      End
      Begin Tables = 
         Begin Table = "MES_接口_生产计划"
            Begin Extent = 
               Top = 31
               Left = 204
               Bottom = 364
               Right = 387
            End
            DisplayFlags = 280
            TopColumn = 14
         End
         Begin Table = "车间生产管理工艺_零件工序_工艺库"
            Begin Extent = 
               Top = 16
               Left = 472
               Bottom = 449
               Right = 684
            End
            DisplayFlags = 280
            TopColumn = 1
         End
         Begin Table = "基础表_工序"
            Begin Extent = 
               Top = 0
               Left = 858
               Bottom = 254
               Right = 1041
            End
            DisplayFlags = 280
            TopColumn = 0
         End
      End
   End
   Begin SQLPane = 
   End
   Begin DataPane = 
      Begin ParameterDefaults = ""
      End
   End
   Begin CriteriaPane = 
      Begin ColumnWidths = 11
         Column = 1440
         Alias = 900
         Table = 2370
         Output = 720
         Append = 1400
         NewValue = 1170
         SortType = 1350
         SortOrder = 1410
         GroupBy = 1350
         Filter = 1350
         Or = 1350
         Or = 1350
         Or = 1350
      End
   End
End
' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'View_标准工艺视图'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPaneCount', @value=1 , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'View_标准工艺视图'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPane1', @value=N'[0E232FF0-B466-11cf-A24F-00AA00A3EFFF, 1.00]
Begin DesignProperties = 
   Begin PaneConfigurations = 
      Begin PaneConfiguration = 0
         NumPanes = 4
         Configuration = "(H (1[40] 4[20] 2[20] 3) )"
      End
      Begin PaneConfiguration = 1
         NumPanes = 3
         Configuration = "(H (1 [50] 4 [25] 3))"
      End
      Begin PaneConfiguration = 2
         NumPanes = 3
         Configuration = "(H (1 [50] 2 [25] 3))"
      End
      Begin PaneConfiguration = 3
         NumPanes = 3
         Configuration = "(H (4 [30] 2 [40] 3))"
      End
      Begin PaneConfiguration = 4
         NumPanes = 2
         Configuration = "(H (1 [56] 3))"
      End
      Begin PaneConfiguration = 5
         NumPanes = 2
         Configuration = "(H (2 [66] 3))"
      End
      Begin PaneConfiguration = 6
         NumPanes = 2
         Configuration = "(H (4 [50] 3))"
      End
      Begin PaneConfiguration = 7
         NumPanes = 1
         Configuration = "(V (3))"
      End
      Begin PaneConfiguration = 8
         NumPanes = 3
         Configuration = "(H (1[56] 4[18] 2) )"
      End
      Begin PaneConfiguration = 9
         NumPanes = 2
         Configuration = "(H (1 [75] 4))"
      End
      Begin PaneConfiguration = 10
         NumPanes = 2
         Configuration = "(H (1[66] 2) )"
      End
      Begin PaneConfiguration = 11
         NumPanes = 2
         Configuration = "(H (4 [60] 2))"
      End
      Begin PaneConfiguration = 12
         NumPanes = 1
         Configuration = "(H (1) )"
      End
      Begin PaneConfiguration = 13
         NumPanes = 1
         Configuration = "(V (4))"
      End
      Begin PaneConfiguration = 14
         NumPanes = 1
         Configuration = "(V (2))"
      End
      ActivePaneConfig = 0
   End
   Begin DiagramPane = 
      Begin Origin = 
         Top = 0
         Left = 0
      End
      Begin Tables = 
         Begin Table = "a"
            Begin Extent = 
               Top = 9
               Left = 57
               Bottom = 201
               Right = 240
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "b"
            Begin Extent = 
               Top = 9
               Left = 297
               Bottom = 201
               Right = 533
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "c"
            Begin Extent = 
               Top = 9
               Left = 590
               Bottom = 201
               Right = 858
            End
            DisplayFlags = 280
            TopColumn = 0
         End
      End
   End
   Begin SQLPane = 
   End
   Begin DataPane = 
      Begin ParameterDefaults = ""
      End
   End
   Begin CriteriaPane = 
      Begin ColumnWidths = 11
         Column = 1440
         Alias = 900
         Table = 1170
         Output = 720
         Append = 1400
         NewValue = 1170
         SortType = 1350
         SortOrder = 1410
         GroupBy = 1350
         Filter = 1350
         Or = 1350
         Or = 1350
         Or = 1350
      End
   End
End
' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'View_工位人员绑定数'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPaneCount', @value=1 , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'View_工位人员绑定数'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPane1', @value=N'[0E232FF0-B466-11cf-A24F-00AA00A3EFFF, 1.00]
Begin DesignProperties = 
   Begin PaneConfigurations = 
      Begin PaneConfiguration = 0
         NumPanes = 4
         Configuration = "(H (1[42] 4[20] 2[10] 3) )"
      End
      Begin PaneConfiguration = 1
         NumPanes = 3
         Configuration = "(H (1 [50] 4 [25] 3))"
      End
      Begin PaneConfiguration = 2
         NumPanes = 3
         Configuration = "(H (1 [50] 2 [25] 3))"
      End
      Begin PaneConfiguration = 3
         NumPanes = 3
         Configuration = "(H (4 [30] 2 [40] 3))"
      End
      Begin PaneConfiguration = 4
         NumPanes = 2
         Configuration = "(H (1 [56] 3))"
      End
      Begin PaneConfiguration = 5
         NumPanes = 2
         Configuration = "(H (2 [66] 3))"
      End
      Begin PaneConfiguration = 6
         NumPanes = 2
         Configuration = "(H (4 [50] 3))"
      End
      Begin PaneConfiguration = 7
         NumPanes = 1
         Configuration = "(V (3))"
      End
      Begin PaneConfiguration = 8
         NumPanes = 3
         Configuration = "(H (1[56] 4[18] 2) )"
      End
      Begin PaneConfiguration = 9
         NumPanes = 2
         Configuration = "(H (1 [75] 4))"
      End
      Begin PaneConfiguration = 10
         NumPanes = 2
         Configuration = "(H (1[66] 2) )"
      End
      Begin PaneConfiguration = 11
         NumPanes = 2
         Configuration = "(H (4 [60] 2))"
      End
      Begin PaneConfiguration = 12
         NumPanes = 1
         Configuration = "(H (1) )"
      End
      Begin PaneConfiguration = 13
         NumPanes = 1
         Configuration = "(V (4))"
      End
      Begin PaneConfiguration = 14
         NumPanes = 1
         Configuration = "(V (2))"
      End
      ActivePaneConfig = 0
   End
   Begin DiagramPane = 
      Begin Origin = 
         Top = 0
         Left = 0
      End
      Begin Tables = 
         Begin Table = "MES_资源主数据"
            Begin Extent = 
               Top = 6
               Left = 38
               Bottom = 146
               Right = 218
            End
            DisplayFlags = 280
            TopColumn = 0
         End
      End
   End
   Begin SQLPane = 
   End
   Begin DataPane = 
      Begin ParameterDefaults = ""
      End
      Begin ColumnWidths = 9
         Width = 284
         Width = 930
         Width = 1035
         Width = 2400
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
      End
   End
   Begin CriteriaPane = 
      Begin ColumnWidths = 11
         Column = 1440
         Alias = 900
         Table = 1170
         Output = 720
         Append = 1400
         NewValue = 1170
         SortType = 1350
         SortOrder = 1410
         GroupBy = 1350
         Filter = 1350
         Or = 1350
         Or = 1350
         Or = 1350
      End
   End
End
' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'View_基础数据_工位'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPaneCount', @value=1 , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'View_基础数据_工位'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPane1', @value=N'[0E232FF0-B466-11cf-A24F-00AA00A3EFFF, 1.00]
Begin DesignProperties = 
   Begin PaneConfigurations = 
      Begin PaneConfiguration = 0
         NumPanes = 4
         Configuration = "(H (1[40] 4[20] 2[20] 3) )"
      End
      Begin PaneConfiguration = 1
         NumPanes = 3
         Configuration = "(H (1 [50] 4 [25] 3))"
      End
      Begin PaneConfiguration = 2
         NumPanes = 3
         Configuration = "(H (1 [50] 2 [25] 3))"
      End
      Begin PaneConfiguration = 3
         NumPanes = 3
         Configuration = "(H (4 [30] 2 [40] 3))"
      End
      Begin PaneConfiguration = 4
         NumPanes = 2
         Configuration = "(H (1 [56] 3))"
      End
      Begin PaneConfiguration = 5
         NumPanes = 2
         Configuration = "(H (2 [66] 3))"
      End
      Begin PaneConfiguration = 6
         NumPanes = 2
         Configuration = "(H (4 [50] 3))"
      End
      Begin PaneConfiguration = 7
         NumPanes = 1
         Configuration = "(V (3))"
      End
      Begin PaneConfiguration = 8
         NumPanes = 3
         Configuration = "(H (1[56] 4[18] 2) )"
      End
      Begin PaneConfiguration = 9
         NumPanes = 2
         Configuration = "(H (1 [75] 4))"
      End
      Begin PaneConfiguration = 10
         NumPanes = 2
         Configuration = "(H (1[66] 2) )"
      End
      Begin PaneConfiguration = 11
         NumPanes = 2
         Configuration = "(H (4 [60] 2))"
      End
      Begin PaneConfiguration = 12
         NumPanes = 1
         Configuration = "(H (1) )"
      End
      Begin PaneConfiguration = 13
         NumPanes = 1
         Configuration = "(V (4))"
      End
      Begin PaneConfiguration = 14
         NumPanes = 1
         Configuration = "(V (2))"
      End
      ActivePaneConfig = 0
   End
   Begin DiagramPane = 
      Begin Origin = 
         Top = 0
         Left = 0
      End
      Begin Tables = 
         Begin Table = "登录基础数据_人员信息"
            Begin Extent = 
               Top = 44
               Left = 613
               Bottom = 329
               Right = 881
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "工位人员绑定表"
            Begin Extent = 
               Top = 9
               Left = 350
               Bottom = 286
               Right = 533
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "班次人员绑定表"
            Begin Extent = 
               Top = 82
               Left = 936
               Bottom = 274
               Right = 1119
            End
            DisplayFlags = 280
            TopColumn = 5
         End
         Begin Table = "班次表"
            Begin Extent = 
               Top = 82
               Left = 1175
               Bottom = 274
               Right = 1358
            End
            DisplayFlags = 280
            TopColumn = 5
         End
         Begin Table = "MES_资源主数据"
            Begin Extent = 
               Top = 9
               Left = 57
               Bottom = 264
               Right = 293
            End
            DisplayFlags = 280
            TopColumn = 0
         End
      End
   End
   Begin SQLPane = 
   End
   Begin DataPane = 
      Begin ParameterDefaults = ""
      End
      Begin ColumnWidths = 9
         Width = 284
         Width = 1000
         Width = 1000
         Width = 1000
         Width = 1000
         Width = 1000
         Width = 1000
         Width = 1000
         Width = 1000
      End
   End
   Begin CriteriaPane = 
      Begin ColumnWidths = 11
         Column = 1440
         Alias = 900
     ' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'View_设备工位人员'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPane2', @value=N'    Table = 1170
         Output = 720
         Append = 1400
         NewValue = 1170
         SortType = 1350
         SortOrder = 1410
         GroupBy = 1350
         Filter = 1350
         Or = 1350
         Or = 1350
         Or = 1350
      End
   End
End
' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'View_设备工位人员'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPaneCount', @value=2 , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'View_设备工位人员'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPane1', @value=N'[0E232FF0-B466-11cf-A24F-00AA00A3EFFF, 1.00]
Begin DesignProperties = 
   Begin PaneConfigurations = 
      Begin PaneConfiguration = 0
         NumPanes = 4
         Configuration = "(H (1[43] 4[22] 2[17] 3) )"
      End
      Begin PaneConfiguration = 1
         NumPanes = 3
         Configuration = "(H (1 [50] 4 [25] 3))"
      End
      Begin PaneConfiguration = 2
         NumPanes = 3
         Configuration = "(H (1 [50] 2 [25] 3))"
      End
      Begin PaneConfiguration = 3
         NumPanes = 3
         Configuration = "(H (4 [30] 2 [40] 3))"
      End
      Begin PaneConfiguration = 4
         NumPanes = 2
         Configuration = "(H (1 [56] 3))"
      End
      Begin PaneConfiguration = 5
         NumPanes = 2
         Configuration = "(H (2 [66] 3))"
      End
      Begin PaneConfiguration = 6
         NumPanes = 2
         Configuration = "(H (4 [50] 3))"
      End
      Begin PaneConfiguration = 7
         NumPanes = 1
         Configuration = "(V (3))"
      End
      Begin PaneConfiguration = 8
         NumPanes = 3
         Configuration = "(H (1[56] 4[18] 2) )"
      End
      Begin PaneConfiguration = 9
         NumPanes = 2
         Configuration = "(H (1 [75] 4))"
      End
      Begin PaneConfiguration = 10
         NumPanes = 2
         Configuration = "(H (1[66] 2) )"
      End
      Begin PaneConfiguration = 11
         NumPanes = 2
         Configuration = "(H (4 [60] 2))"
      End
      Begin PaneConfiguration = 12
         NumPanes = 1
         Configuration = "(H (1) )"
      End
      Begin PaneConfiguration = 13
         NumPanes = 1
         Configuration = "(V (4))"
      End
      Begin PaneConfiguration = 14
         NumPanes = 1
         Configuration = "(V (2))"
      End
      ActivePaneConfig = 0
   End
   Begin DiagramPane = 
      Begin Origin = 
         Top = 0
         Left = 0
      End
      Begin Tables = 
         Begin Table = "b"
            Begin Extent = 
               Top = 6
               Left = 330
               Bottom = 376
               Right = 543
            End
            DisplayFlags = 280
            TopColumn = 55
         End
         Begin Table = "物料基础数据_零件图纸"
            Begin Extent = 
               Top = 229
               Left = 673
               Bottom = 531
               Right = 880
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "MES_资源主数据"
            Begin Extent = 
               Top = 21
               Left = 633
               Bottom = 198
               Right = 869
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "a"
            Begin Extent = 
               Top = 6
               Left = 38
               Bottom = 348
               Right = 272
            End
            DisplayFlags = 280
            TopColumn = 27
         End
      End
   End
   Begin SQLPane = 
   End
   Begin DataPane = 
      Begin ParameterDefaults = ""
      End
      Begin ColumnWidths = 86
         Width = 284
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
     ' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'View_生产订单_MES'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPane2', @value=N'    Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1010
         Width = 1010
         Width = 1010
         Width = 1010
         Width = 1010
         Width = 1010
         Width = 1010
         Width = 1010
         Width = 1010
         Width = 1010
         Width = 1010
         Width = 1010
         Width = 1010
         Width = 1010
         Width = 1010
         Width = 1010
         Width = 1010
         Width = 1010
         Width = 1010
         Width = 1010
         Width = 1010
         Width = 1010
         Width = 1010
         Width = 1010
         Width = 1010
         Width = 1010
         Width = 1010
         Width = 1010
         Width = 1010
         Width = 1010
         Width = 1010
         Width = 1010
         Width = 1010
         Width = 1010
         Width = 1010
         Width = 1010
         Width = 1010
         Width = 1010
         Width = 1010
         Width = 1010
         Width = 1010
         Width = 1010
         Width = 1010
         Width = 1010
         Width = 1010
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
      End
   End
   Begin CriteriaPane = 
      Begin ColumnWidths = 11
         Column = 1440
         Alias = 2870
         Table = 1170
         Output = 720
         Append = 1400
         NewValue = 1170
         SortType = 1350
         SortOrder = 1410
         GroupBy = 1350
         Filter = 1350
         Or = 1350
         Or = 1350
         Or = 1350
      End
   End
End
' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'View_生产订单_MES'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPaneCount', @value=2 , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'View_生产订单_MES'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPane1', @value=N'[0E232FF0-B466-11cf-A24F-00AA00A3EFFF, 1.00]
Begin DesignProperties = 
   Begin PaneConfigurations = 
      Begin PaneConfiguration = 0
         NumPanes = 4
         Configuration = "(H (1[40] 4[20] 2[20] 3) )"
      End
      Begin PaneConfiguration = 1
         NumPanes = 3
         Configuration = "(H (1 [50] 4 [25] 3))"
      End
      Begin PaneConfiguration = 2
         NumPanes = 3
         Configuration = "(H (1 [50] 2 [25] 3))"
      End
      Begin PaneConfiguration = 3
         NumPanes = 3
         Configuration = "(H (4 [30] 2 [40] 3))"
      End
      Begin PaneConfiguration = 4
         NumPanes = 2
         Configuration = "(H (1 [56] 3))"
      End
      Begin PaneConfiguration = 5
         NumPanes = 2
         Configuration = "(H (2 [66] 3))"
      End
      Begin PaneConfiguration = 6
         NumPanes = 2
         Configuration = "(H (4 [50] 3))"
      End
      Begin PaneConfiguration = 7
         NumPanes = 1
         Configuration = "(V (3))"
      End
      Begin PaneConfiguration = 8
         NumPanes = 3
         Configuration = "(H (1[56] 4[18] 2) )"
      End
      Begin PaneConfiguration = 9
         NumPanes = 2
         Configuration = "(H (1 [75] 4))"
      End
      Begin PaneConfiguration = 10
         NumPanes = 2
         Configuration = "(H (1[66] 2) )"
      End
      Begin PaneConfiguration = 11
         NumPanes = 2
         Configuration = "(H (4 [60] 2))"
      End
      Begin PaneConfiguration = 12
         NumPanes = 1
         Configuration = "(H (1) )"
      End
      Begin PaneConfiguration = 13
         NumPanes = 1
         Configuration = "(V (4))"
      End
      Begin PaneConfiguration = 14
         NumPanes = 1
         Configuration = "(V (2))"
      End
      ActivePaneConfig = 0
   End
   Begin DiagramPane = 
      Begin Origin = 
         Top = 0
         Left = 0
      End
      Begin Tables = 
         Begin Table = "OWOR"
            Begin Extent = 
               Top = 6
               Left = 38
               Bottom = 146
               Right = 260
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "OWR1"
            Begin Extent = 
               Top = 6
               Left = 376
               Bottom = 146
               Right = 621
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "OWR4"
            Begin Extent = 
               Top = 0
               Left = 751
               Bottom = 140
               Right = 944
            End
            DisplayFlags = 280
            TopColumn = 0
         End
      End
   End
   Begin SQLPane = 
   End
   Begin DataPane = 
      Begin ParameterDefaults = ""
      End
      Begin ColumnWidths = 28
         Width = 284
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
      End
   End
   Begin CriteriaPane = 
      Begin ColumnWidths = 11
         Column = 1440
         Alias = 900
         Table = 1170
         Output = 720
         Append = 1400
         NewValue = 1170
         S' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'View_生产订单Temp_ERP'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPane2', @value=N'ortType = 1350
         SortOrder = 1410
         GroupBy = 1350
         Filter = 1350
         Or = 1350
         Or = 1350
         Or = 1350
      End
   End
End
' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'View_生产订单Temp_ERP'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPaneCount', @value=2 , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'View_生产订单Temp_ERP'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPane1', @value=N'[0E232FF0-B466-11cf-A24F-00AA00A3EFFF, 1.00]
Begin DesignProperties = 
   Begin PaneConfigurations = 
      Begin PaneConfiguration = 0
         NumPanes = 4
         Configuration = "(H (1[40] 4[20] 2[20] 3) )"
      End
      Begin PaneConfiguration = 1
         NumPanes = 3
         Configuration = "(H (1 [50] 4 [25] 3))"
      End
      Begin PaneConfiguration = 2
         NumPanes = 3
         Configuration = "(H (1 [50] 2 [25] 3))"
      End
      Begin PaneConfiguration = 3
         NumPanes = 3
         Configuration = "(H (4 [30] 2 [40] 3))"
      End
      Begin PaneConfiguration = 4
         NumPanes = 2
         Configuration = "(H (1 [56] 3))"
      End
      Begin PaneConfiguration = 5
         NumPanes = 2
         Configuration = "(H (2 [66] 3))"
      End
      Begin PaneConfiguration = 6
         NumPanes = 2
         Configuration = "(H (4 [50] 3))"
      End
      Begin PaneConfiguration = 7
         NumPanes = 1
         Configuration = "(V (3))"
      End
      Begin PaneConfiguration = 8
         NumPanes = 3
         Configuration = "(H (1[56] 4[18] 2) )"
      End
      Begin PaneConfiguration = 9
         NumPanes = 2
         Configuration = "(H (1 [75] 4))"
      End
      Begin PaneConfiguration = 10
         NumPanes = 2
         Configuration = "(H (1[66] 2) )"
      End
      Begin PaneConfiguration = 11
         NumPanes = 2
         Configuration = "(H (4 [60] 2))"
      End
      Begin PaneConfiguration = 12
         NumPanes = 1
         Configuration = "(H (1) )"
      End
      Begin PaneConfiguration = 13
         NumPanes = 1
         Configuration = "(V (4))"
      End
      Begin PaneConfiguration = 14
         NumPanes = 1
         Configuration = "(V (2))"
      End
      ActivePaneConfig = 0
   End
   Begin DiagramPane = 
      Begin Origin = 
         Top = 0
         Left = 0
      End
      Begin Tables = 
         Begin Table = "b"
            Begin Extent = 
               Top = 9
               Left = 57
               Bottom = 201
               Right = 269
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "物料基础数据_零件图纸"
            Begin Extent = 
               Top = 9
               Left = 326
               Bottom = 201
               Right = 533
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "MES_资源主数据"
            Begin Extent = 
               Top = 9
               Left = 590
               Bottom = 201
               Right = 826
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "a"
            Begin Extent = 
               Top = 9
               Left = 883
               Bottom = 201
               Right = 1113
            End
            DisplayFlags = 280
            TopColumn = 0
         End
      End
   End
   Begin SQLPane = 
   End
   Begin DataPane = 
      Begin ParameterDefaults = ""
      End
   End
   Begin CriteriaPane = 
      Begin ColumnWidths = 11
         Column = 1440
         Alias = 900
         Table = 1170
         Output = 720
         Append = 1400
         NewValue = 1170
         SortType = 1350
         SortOrder = 1410
         GroupBy = 1350
         Filter = 1350
         Or = 1350
         Or = 1350
         Or = 1350
      End
   End
End
' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'View_生产订单全部（包括已关闭）'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPaneCount', @value=1 , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'View_生产订单全部（包括已关闭）'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPane1', @value=N'[0E232FF0-B466-11cf-A24F-00AA00A3EFFF, 1.00]
Begin DesignProperties = 
   Begin PaneConfigurations = 
      Begin PaneConfiguration = 0
         NumPanes = 4
         Configuration = "(H (1[40] 4[20] 2[20] 3) )"
      End
      Begin PaneConfiguration = 1
         NumPanes = 3
         Configuration = "(H (1 [50] 4 [25] 3))"
      End
      Begin PaneConfiguration = 2
         NumPanes = 3
         Configuration = "(H (1 [50] 2 [25] 3))"
      End
      Begin PaneConfiguration = 3
         NumPanes = 3
         Configuration = "(H (4 [30] 2 [40] 3))"
      End
      Begin PaneConfiguration = 4
         NumPanes = 2
         Configuration = "(H (1 [56] 3))"
      End
      Begin PaneConfiguration = 5
         NumPanes = 2
         Configuration = "(H (2 [66] 3))"
      End
      Begin PaneConfiguration = 6
         NumPanes = 2
         Configuration = "(H (4 [50] 3))"
      End
      Begin PaneConfiguration = 7
         NumPanes = 1
         Configuration = "(V (3))"
      End
      Begin PaneConfiguration = 8
         NumPanes = 3
         Configuration = "(H (1[56] 4[18] 2) )"
      End
      Begin PaneConfiguration = 9
         NumPanes = 2
         Configuration = "(H (1 [75] 4))"
      End
      Begin PaneConfiguration = 10
         NumPanes = 2
         Configuration = "(H (1[66] 2) )"
      End
      Begin PaneConfiguration = 11
         NumPanes = 2
         Configuration = "(H (4 [60] 2))"
      End
      Begin PaneConfiguration = 12
         NumPanes = 1
         Configuration = "(H (1) )"
      End
      Begin PaneConfiguration = 13
         NumPanes = 1
         Configuration = "(V (4))"
      End
      Begin PaneConfiguration = 14
         NumPanes = 1
         Configuration = "(V (2))"
      End
      ActivePaneConfig = 0
   End
   Begin DiagramPane = 
      Begin Origin = 
         Top = 0
         Left = 0
      End
      Begin Tables = 
         Begin Table = "v"
            Begin Extent = 
               Top = 9
               Left = 57
               Bottom = 201
               Right = 285
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "zj_收检"
            Begin Extent = 
               Top = 9
               Left = 342
               Bottom = 175
               Right = 570
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "zj_终检数量"
            Begin Extent = 
               Top = 9
               Left = 627
               Bottom = 175
               Right = 891
            End
            DisplayFlags = 280
            TopColumn = 0
         End
      End
   End
   Begin SQLPane = 
   End
   Begin DataPane = 
      Begin ParameterDefaults = ""
      End
      Begin ColumnWidths = 9
         Width = 284
         Width = 1000
         Width = 1000
         Width = 1000
         Width = 1000
         Width = 1000
         Width = 1000
         Width = 1000
         Width = 1000
      End
   End
   Begin CriteriaPane = 
      Begin ColumnWidths = 13
         Column = 1440
         Alias = 900
         Table = 1170
         Output = 720
         Append = 1400
         NewValue = 1170
         SortType = 1350
         SortOrder = 1410
         GroupBy = 1350
         Filter = 1350
         Or = 1350
         Or = 1350
         Or = 1350
         Or = 1350
      End
   End
End
' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'View_生产订单完工'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPaneCount', @value=1 , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'View_生产订单完工'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPane1', @value=N'[0E232FF0-B466-11cf-A24F-00AA00A3EFFF, 1.00]
Begin DesignProperties = 
   Begin PaneConfigurations = 
      Begin PaneConfiguration = 0
         NumPanes = 4
         Configuration = "(H (1[40] 4[20] 2[20] 3) )"
      End
      Begin PaneConfiguration = 1
         NumPanes = 3
         Configuration = "(H (1 [50] 4 [25] 3))"
      End
      Begin PaneConfiguration = 2
         NumPanes = 3
         Configuration = "(H (1 [50] 2 [25] 3))"
      End
      Begin PaneConfiguration = 3
         NumPanes = 3
         Configuration = "(H (4 [30] 2 [40] 3))"
      End
      Begin PaneConfiguration = 4
         NumPanes = 2
         Configuration = "(H (1 [56] 3))"
      End
      Begin PaneConfiguration = 5
         NumPanes = 2
         Configuration = "(H (2 [66] 3))"
      End
      Begin PaneConfiguration = 6
         NumPanes = 2
         Configuration = "(H (4 [50] 3))"
      End
      Begin PaneConfiguration = 7
         NumPanes = 1
         Configuration = "(V (3))"
      End
      Begin PaneConfiguration = 8
         NumPanes = 3
         Configuration = "(H (1[56] 4[18] 2) )"
      End
      Begin PaneConfiguration = 9
         NumPanes = 2
         Configuration = "(H (1 [75] 4))"
      End
      Begin PaneConfiguration = 10
         NumPanes = 2
         Configuration = "(H (1[66] 2) )"
      End
      Begin PaneConfiguration = 11
         NumPanes = 2
         Configuration = "(H (4 [60] 2))"
      End
      Begin PaneConfiguration = 12
         NumPanes = 1
         Configuration = "(H (1) )"
      End
      Begin PaneConfiguration = 13
         NumPanes = 1
         Configuration = "(V (4))"
      End
      Begin PaneConfiguration = 14
         NumPanes = 1
         Configuration = "(V (2))"
      End
      ActivePaneConfig = 0
   End
   Begin DiagramPane = 
      Begin Origin = 
         Top = 0
         Left = 0
      End
      Begin Tables = 
         Begin Table = "o"
            Begin Extent = 
               Top = 9
               Left = 57
               Bottom = 408
               Right = 288
            End
            DisplayFlags = 280
            TopColumn = 26
         End
         Begin Table = "View_工位人员绑定数"
            Begin Extent = 
               Top = 9
               Left = 1188
               Bottom = 175
               Right = 1382
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "c"
            Begin Extent = 
               Top = 9
               Left = 345
               Bottom = 392
               Right = 557
            End
            DisplayFlags = 280
            TopColumn = 14
         End
         Begin Table = "m"
            Begin Extent = 
               Top = 9
               Left = 614
               Bottom = 385
               Right = 844
            End
            DisplayFlags = 280
            TopColumn = 23
         End
         Begin Table = "s"
            Begin Extent = 
               Top = 9
               Left = 901
               Bottom = 381
               Right = 1131
            End
            DisplayFlags = 280
            TopColumn = 19
         End
      End
   End
   Begin SQLPane = 
   End
   Begin DataPane = 
      Begin ParameterDefaults = ""
      End
   End
   Begin CriteriaPane = 
      Begin ColumnWidths = 11
         Column = 1440
         Alias = 900
         Table = 1170
         Output = 720
         Append = 1400
         NewValue = 1170
         SortType = 1350
         SortOrder = 1410
         GroupBy = 1350
         Filter = 1350
         Or = 1350
         Or = 1350
         Or = 1350
      End
   ' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'View_生产工时视图'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPane2', @value=N'End
End
' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'View_生产工时视图'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPaneCount', @value=2 , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'View_生产工时视图'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPane1', @value=N'[0E232FF0-B466-11cf-A24F-00AA00A3EFFF, 1.00]
Begin DesignProperties = 
   Begin PaneConfigurations = 
      Begin PaneConfiguration = 0
         NumPanes = 4
         Configuration = "(H (1[40] 4[20] 2[20] 3) )"
      End
      Begin PaneConfiguration = 1
         NumPanes = 3
         Configuration = "(H (1 [50] 4 [25] 3))"
      End
      Begin PaneConfiguration = 2
         NumPanes = 3
         Configuration = "(H (1 [50] 2 [25] 3))"
      End
      Begin PaneConfiguration = 3
         NumPanes = 3
         Configuration = "(H (4 [30] 2 [40] 3))"
      End
      Begin PaneConfiguration = 4
         NumPanes = 2
         Configuration = "(H (1 [56] 3))"
      End
      Begin PaneConfiguration = 5
         NumPanes = 2
         Configuration = "(H (2 [66] 3))"
      End
      Begin PaneConfiguration = 6
         NumPanes = 2
         Configuration = "(H (4 [50] 3))"
      End
      Begin PaneConfiguration = 7
         NumPanes = 1
         Configuration = "(V (3))"
      End
      Begin PaneConfiguration = 8
         NumPanes = 3
         Configuration = "(H (1[56] 4[18] 2) )"
      End
      Begin PaneConfiguration = 9
         NumPanes = 2
         Configuration = "(H (1 [75] 4))"
      End
      Begin PaneConfiguration = 10
         NumPanes = 2
         Configuration = "(H (1[66] 2) )"
      End
      Begin PaneConfiguration = 11
         NumPanes = 2
         Configuration = "(H (4 [60] 2))"
      End
      Begin PaneConfiguration = 12
         NumPanes = 1
         Configuration = "(H (1) )"
      End
      Begin PaneConfiguration = 13
         NumPanes = 1
         Configuration = "(V (4))"
      End
      Begin PaneConfiguration = 14
         NumPanes = 1
         Configuration = "(V (2))"
      End
      ActivePaneConfig = 0
   End
   Begin DiagramPane = 
      Begin Origin = 
         Top = 0
         Left = 0
      End
      Begin Tables = 
         Begin Table = "车间生产管理工艺_零件生产工艺_工艺库"
            Begin Extent = 
               Top = 9
               Left = 57
               Bottom = 462
               Right = 344
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "MES_接口_生产计划"
            Begin Extent = 
               Top = 12
               Left = 428
               Bottom = 474
               Right = 818
            End
            DisplayFlags = 280
            TopColumn = 22
         End
      End
   End
   Begin SQLPane = 
   End
   Begin DataPane = 
      Begin ParameterDefaults = ""
      End
   End
   Begin CriteriaPane = 
      Begin ColumnWidths = 11
         Column = 1440
         Alias = 900
         Table = 2470
         Output = 720
         Append = 1400
         NewValue = 1170
         SortType = 1350
         SortOrder = 1410
         GroupBy = 1350
         Filter = 1350
         Or = 1350
         Or = 1350
         Or = 1350
      End
   End
End
' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'View_生产工艺视图'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPaneCount', @value=1 , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'View_生产工艺视图'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPane1', @value=N'[0E232FF0-B466-11cf-A24F-00AA00A3EFFF, 1.00]
Begin DesignProperties = 
   Begin PaneConfigurations = 
      Begin PaneConfiguration = 0
         NumPanes = 4
         Configuration = "(H (1[40] 4[20] 2[20] 3) )"
      End
      Begin PaneConfiguration = 1
         NumPanes = 3
         Configuration = "(H (1 [50] 4 [25] 3))"
      End
      Begin PaneConfiguration = 2
         NumPanes = 3
         Configuration = "(H (1 [50] 2 [25] 3))"
      End
      Begin PaneConfiguration = 3
         NumPanes = 3
         Configuration = "(H (4 [30] 2 [40] 3))"
      End
      Begin PaneConfiguration = 4
         NumPanes = 2
         Configuration = "(H (1 [56] 3))"
      End
      Begin PaneConfiguration = 5
         NumPanes = 2
         Configuration = "(H (2 [66] 3))"
      End
      Begin PaneConfiguration = 6
         NumPanes = 2
         Configuration = "(H (4 [50] 3))"
      End
      Begin PaneConfiguration = 7
         NumPanes = 1
         Configuration = "(V (3))"
      End
      Begin PaneConfiguration = 8
         NumPanes = 3
         Configuration = "(H (1[56] 4[18] 2) )"
      End
      Begin PaneConfiguration = 9
         NumPanes = 2
         Configuration = "(H (1 [75] 4))"
      End
      Begin PaneConfiguration = 10
         NumPanes = 2
         Configuration = "(H (1[66] 2) )"
      End
      Begin PaneConfiguration = 11
         NumPanes = 2
         Configuration = "(H (4 [60] 2))"
      End
      Begin PaneConfiguration = 12
         NumPanes = 1
         Configuration = "(H (1) )"
      End
      Begin PaneConfiguration = 13
         NumPanes = 1
         Configuration = "(V (4))"
      End
      Begin PaneConfiguration = 14
         NumPanes = 1
         Configuration = "(V (2))"
      End
      ActivePaneConfig = 0
   End
   Begin DiagramPane = 
      Begin Origin = 
         Top = 0
         Left = 0
      End
      Begin Tables = 
         Begin Table = "MES_接口_生产计划"
            Begin Extent = 
               Top = 9
               Left = 57
               Bottom = 201
               Right = 287
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "物料基础数据_零件图纸"
            Begin Extent = 
               Top = 9
               Left = 344
               Bottom = 201
               Right = 551
            End
            DisplayFlags = 280
            TopColumn = 0
         End
      End
   End
   Begin SQLPane = 
   End
   Begin DataPane = 
      Begin ParameterDefaults = ""
      End
   End
   Begin CriteriaPane = 
      Begin ColumnWidths = 11
         Column = 1440
         Alias = 900
         Table = 2680
         Output = 720
         Append = 1400
         NewValue = 1170
         SortType = 1350
         SortOrder = 1410
         GroupBy = 1350
         Filter = 1350
         Or = 1350
         Or = 1350
         Or = 1350
      End
   End
End
' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'View_生产计划零件图纸视图'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPaneCount', @value=1 , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'View_生产计划零件图纸视图'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPane1', @value=N'[0E232FF0-B466-11cf-A24F-00AA00A3EFFF, 1.00]
Begin DesignProperties = 
   Begin PaneConfigurations = 
      Begin PaneConfiguration = 0
         NumPanes = 4
         Configuration = "(H (1[40] 4[20] 2[20] 3) )"
      End
      Begin PaneConfiguration = 1
         NumPanes = 3
         Configuration = "(H (1 [50] 4 [25] 3))"
      End
      Begin PaneConfiguration = 2
         NumPanes = 3
         Configuration = "(H (1 [50] 2 [25] 3))"
      End
      Begin PaneConfiguration = 3
         NumPanes = 3
         Configuration = "(H (4 [30] 2 [40] 3))"
      End
      Begin PaneConfiguration = 4
         NumPanes = 2
         Configuration = "(H (1 [56] 3))"
      End
      Begin PaneConfiguration = 5
         NumPanes = 2
         Configuration = "(H (2 [66] 3))"
      End
      Begin PaneConfiguration = 6
         NumPanes = 2
         Configuration = "(H (4 [50] 3))"
      End
      Begin PaneConfiguration = 7
         NumPanes = 1
         Configuration = "(V (3))"
      End
      Begin PaneConfiguration = 8
         NumPanes = 3
         Configuration = "(H (1[56] 4[18] 2) )"
      End
      Begin PaneConfiguration = 9
         NumPanes = 2
         Configuration = "(H (1 [75] 4))"
      End
      Begin PaneConfiguration = 10
         NumPanes = 2
         Configuration = "(H (1[66] 2) )"
      End
      Begin PaneConfiguration = 11
         NumPanes = 2
         Configuration = "(H (4 [60] 2))"
      End
      Begin PaneConfiguration = 12
         NumPanes = 1
         Configuration = "(H (1) )"
      End
      Begin PaneConfiguration = 13
         NumPanes = 1
         Configuration = "(V (4))"
      End
      Begin PaneConfiguration = 14
         NumPanes = 1
         Configuration = "(V (2))"
      End
      ActivePaneConfig = 0
   End
   Begin DiagramPane = 
      Begin Origin = 
         Top = 0
         Left = 0
      End
      Begin Tables = 
         Begin Table = "t1"
            Begin Extent = 
               Top = 9
               Left = 57
               Bottom = 201
               Right = 264
            End
            DisplayFlags = 280
            TopColumn = 4
         End
         Begin Table = "t2"
            Begin Extent = 
               Top = 9
               Left = 321
               Bottom = 201
               Right = 515
            End
            DisplayFlags = 280
            TopColumn = 9
         End
      End
   End
   Begin SQLPane = 
   End
   Begin DataPane = 
      Begin ParameterDefaults = ""
      End
   End
   Begin CriteriaPane = 
      Begin ColumnWidths = 11
         Column = 1440
         Alias = 900
         Table = 1170
         Output = 720
         Append = 1400
         NewValue = 1170
         SortType = 1350
         SortOrder = 1410
         GroupBy = 1350
         Filter = 1350
         Or = 1350
         Or = 1350
         Or = 1350
      End
   End
End
' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'View_图纸视图'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPaneCount', @value=1 , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'View_图纸视图'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPane1', @value=N'[0E232FF0-B466-11cf-A24F-00AA00A3EFFF, 1.00]
Begin DesignProperties = 
   Begin PaneConfigurations = 
      Begin PaneConfiguration = 0
         NumPanes = 4
         Configuration = "(H (1[40] 4[20] 2[20] 3) )"
      End
      Begin PaneConfiguration = 1
         NumPanes = 3
         Configuration = "(H (1 [50] 4 [25] 3))"
      End
      Begin PaneConfiguration = 2
         NumPanes = 3
         Configuration = "(H (1 [50] 2 [25] 3))"
      End
      Begin PaneConfiguration = 3
         NumPanes = 3
         Configuration = "(H (4 [30] 2 [40] 3))"
      End
      Begin PaneConfiguration = 4
         NumPanes = 2
         Configuration = "(H (1 [56] 3))"
      End
      Begin PaneConfiguration = 5
         NumPanes = 2
         Configuration = "(H (2 [66] 3))"
      End
      Begin PaneConfiguration = 6
         NumPanes = 2
         Configuration = "(H (4 [50] 3))"
      End
      Begin PaneConfiguration = 7
         NumPanes = 1
         Configuration = "(V (3))"
      End
      Begin PaneConfiguration = 8
         NumPanes = 3
         Configuration = "(H (1[56] 4[18] 2) )"
      End
      Begin PaneConfiguration = 9
         NumPanes = 2
         Configuration = "(H (1 [75] 4))"
      End
      Begin PaneConfiguration = 10
         NumPanes = 2
         Configuration = "(H (1[66] 2) )"
      End
      Begin PaneConfiguration = 11
         NumPanes = 2
         Configuration = "(H (4 [60] 2))"
      End
      Begin PaneConfiguration = 12
         NumPanes = 1
         Configuration = "(H (1) )"
      End
      Begin PaneConfiguration = 13
         NumPanes = 1
         Configuration = "(V (4))"
      End
      Begin PaneConfiguration = 14
         NumPanes = 1
         Configuration = "(V (2))"
      End
      ActivePaneConfig = 0
   End
   Begin DiagramPane = 
      Begin Origin = 
         Top = 0
         Left = 0
      End
      Begin Tables = 
         Begin Table = "v"
            Begin Extent = 
               Top = 6
               Left = 38
               Bottom = 301
               Right = 211
            End
            DisplayFlags = 280
            TopColumn = 15
         End
         Begin Table = "zj_收检"
            Begin Extent = 
               Top = 14
               Left = 259
               Bottom = 135
               Right = 420
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "jl"
            Begin Extent = 
               Top = 55
               Left = 455
               Bottom = 195
               Right = 616
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "s"
            Begin Extent = 
               Top = 3
               Left = 645
               Bottom = 403
               Right = 929
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "sl"
            Begin Extent = 
               Top = 220
               Left = 1285
               Bottom = 360
               Right = 1505
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "fl"
            Begin Extent = 
               Top = 9
               Left = 986
               Bottom = 149
               Right = 1198
            End
            DisplayFlags = 280
            TopColumn = 0
         End
      End
   End
   Begin SQLPane = 
   End
   Begin DataPane = 
      Begin ParameterDefaults = ""
      End
      Begin ColumnWidths = 9
         Width = 284
         Width = 1500
         Width = 1500
         Width = 1500
         W' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'View_外协报表视图'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPane2', @value=N'idth = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
      End
   End
   Begin CriteriaPane = 
      Begin ColumnWidths = 11
         Column = 1440
         Alias = 900
         Table = 1170
         Output = 720
         Append = 1400
         NewValue = 1170
         SortType = 1350
         SortOrder = 1410
         GroupBy = 1350
         Filter = 1350
         Or = 1350
         Or = 1350
         Or = 1350
      End
   End
End
' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'View_外协报表视图'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPaneCount', @value=2 , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'View_外协报表视图'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPane1', @value=N'[0E232FF0-B466-11cf-A24F-00AA00A3EFFF, 1.00]
Begin DesignProperties = 
   Begin PaneConfigurations = 
      Begin PaneConfiguration = 0
         NumPanes = 4
         Configuration = "(H (1[40] 4[20] 2[20] 3) )"
      End
      Begin PaneConfiguration = 1
         NumPanes = 3
         Configuration = "(H (1 [50] 4 [25] 3))"
      End
      Begin PaneConfiguration = 2
         NumPanes = 3
         Configuration = "(H (1 [50] 2 [25] 3))"
      End
      Begin PaneConfiguration = 3
         NumPanes = 3
         Configuration = "(H (4 [30] 2 [40] 3))"
      End
      Begin PaneConfiguration = 4
         NumPanes = 2
         Configuration = "(H (1 [56] 3))"
      End
      Begin PaneConfiguration = 5
         NumPanes = 2
         Configuration = "(H (2 [66] 3))"
      End
      Begin PaneConfiguration = 6
         NumPanes = 2
         Configuration = "(H (4 [50] 3))"
      End
      Begin PaneConfiguration = 7
         NumPanes = 1
         Configuration = "(V (3))"
      End
      Begin PaneConfiguration = 8
         NumPanes = 3
         Configuration = "(H (1[56] 4[18] 2) )"
      End
      Begin PaneConfiguration = 9
         NumPanes = 2
         Configuration = "(H (1 [75] 4))"
      End
      Begin PaneConfiguration = 10
         NumPanes = 2
         Configuration = "(H (1[66] 2) )"
      End
      Begin PaneConfiguration = 11
         NumPanes = 2
         Configuration = "(H (4 [60] 2))"
      End
      Begin PaneConfiguration = 12
         NumPanes = 1
         Configuration = "(H (1) )"
      End
      Begin PaneConfiguration = 13
         NumPanes = 1
         Configuration = "(V (4))"
      End
      Begin PaneConfiguration = 14
         NumPanes = 1
         Configuration = "(V (2))"
      End
      ActivePaneConfig = 0
   End
   Begin DiagramPane = 
      Begin Origin = 
         Top = 0
         Left = 0
      End
      Begin Tables = 
         Begin Table = "a"
            Begin Extent = 
               Top = 9
               Left = 57
               Bottom = 201
               Right = 269
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "b"
            Begin Extent = 
               Top = 9
               Left = 326
               Bottom = 201
               Right = 538
            End
            DisplayFlags = 280
            TopColumn = 23
         End
      End
   End
   Begin SQLPane = 
   End
   Begin DataPane = 
      Begin ParameterDefaults = ""
      End
   End
   Begin CriteriaPane = 
      Begin ColumnWidths = 11
         Column = 1440
         Alias = 900
         Table = 1170
         Output = 720
         Append = 1400
         NewValue = 1170
         SortType = 1350
         SortOrder = 1410
         GroupBy = 1350
         Filter = 1350
         Or = 1350
         Or = 1350
         Or = 1350
      End
   End
End
' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'View_外协质检'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPaneCount', @value=1 , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'View_外协质检'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPane1', @value=N'[0E232FF0-B466-11cf-A24F-00AA00A3EFFF, 1.00]
Begin DesignProperties = 
   Begin PaneConfigurations = 
      Begin PaneConfiguration = 0
         NumPanes = 4
         Configuration = "(H (1[40] 4[20] 2[20] 3) )"
      End
      Begin PaneConfiguration = 1
         NumPanes = 3
         Configuration = "(H (1 [50] 4 [25] 3))"
      End
      Begin PaneConfiguration = 2
         NumPanes = 3
         Configuration = "(H (1 [50] 2 [25] 3))"
      End
      Begin PaneConfiguration = 3
         NumPanes = 3
         Configuration = "(H (4 [30] 2 [40] 3))"
      End
      Begin PaneConfiguration = 4
         NumPanes = 2
         Configuration = "(H (1 [56] 3))"
      End
      Begin PaneConfiguration = 5
         NumPanes = 2
         Configuration = "(H (2 [66] 3))"
      End
      Begin PaneConfiguration = 6
         NumPanes = 2
         Configuration = "(H (4 [50] 3))"
      End
      Begin PaneConfiguration = 7
         NumPanes = 1
         Configuration = "(V (3))"
      End
      Begin PaneConfiguration = 8
         NumPanes = 3
         Configuration = "(H (1[56] 4[18] 2) )"
      End
      Begin PaneConfiguration = 9
         NumPanes = 2
         Configuration = "(H (1 [75] 4))"
      End
      Begin PaneConfiguration = 10
         NumPanes = 2
         Configuration = "(H (1[66] 2) )"
      End
      Begin PaneConfiguration = 11
         NumPanes = 2
         Configuration = "(H (4 [60] 2))"
      End
      Begin PaneConfiguration = 12
         NumPanes = 1
         Configuration = "(H (1) )"
      End
      Begin PaneConfiguration = 13
         NumPanes = 1
         Configuration = "(V (4))"
      End
      Begin PaneConfiguration = 14
         NumPanes = 1
         Configuration = "(V (2))"
      End
      ActivePaneConfig = 0
   End
   Begin DiagramPane = 
      Begin Origin = 
         Top = 0
         Left = 0
      End
      Begin Tables = 
         Begin Table = "o"
            Begin Extent = 
               Top = 9
               Left = 57
               Bottom = 201
               Right = 288
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "c"
            Begin Extent = 
               Top = 9
               Left = 345
               Bottom = 201
               Right = 557
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "m"
            Begin Extent = 
               Top = 9
               Left = 614
               Bottom = 201
               Right = 844
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "s"
            Begin Extent = 
               Top = 9
               Left = 901
               Bottom = 201
               Right = 1131
            End
            DisplayFlags = 280
            TopColumn = 0
         End
      End
   End
   Begin SQLPane = 
   End
   Begin DataPane = 
      Begin ParameterDefaults = ""
      End
      Begin ColumnWidths = 9
         Width = 284
         Width = 1000
         Width = 1000
         Width = 1000
         Width = 1000
         Width = 1000
         Width = 1000
         Width = 1000
         Width = 1000
      End
   End
   Begin CriteriaPane = 
      Begin ColumnWidths = 11
         Column = 1440
         Alias = 900
         Table = 1170
         Output = 720
         Append = 1400
         NewValue = 1170
         SortType = 1350
         SortOrder = 1410
         GroupBy = 1350
         Filter = 1350
         Or = 1350
         Or = 1350
         Or = 1350
      End
   End
End
' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'View_校验后的生产工时'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPaneCount', @value=1 , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'View_校验后的生产工时'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPane1', @value=N'[0E232FF0-B466-11cf-A24F-00AA00A3EFFF, 1.00]
Begin DesignProperties = 
   Begin PaneConfigurations = 
      Begin PaneConfiguration = 0
         NumPanes = 4
         Configuration = "(H (1[40] 4[20] 2[20] 3) )"
      End
      Begin PaneConfiguration = 1
         NumPanes = 3
         Configuration = "(H (1 [50] 4 [25] 3))"
      End
      Begin PaneConfiguration = 2
         NumPanes = 3
         Configuration = "(H (1 [50] 2 [25] 3))"
      End
      Begin PaneConfiguration = 3
         NumPanes = 3
         Configuration = "(H (4 [30] 2 [40] 3))"
      End
      Begin PaneConfiguration = 4
         NumPanes = 2
         Configuration = "(H (1 [56] 3))"
      End
      Begin PaneConfiguration = 5
         NumPanes = 2
         Configuration = "(H (2 [66] 3))"
      End
      Begin PaneConfiguration = 6
         NumPanes = 2
         Configuration = "(H (4 [50] 3))"
      End
      Begin PaneConfiguration = 7
         NumPanes = 1
         Configuration = "(V (3))"
      End
      Begin PaneConfiguration = 8
         NumPanes = 3
         Configuration = "(H (1[56] 4[18] 2) )"
      End
      Begin PaneConfiguration = 9
         NumPanes = 2
         Configuration = "(H (1 [75] 4))"
      End
      Begin PaneConfiguration = 10
         NumPanes = 2
         Configuration = "(H (1[66] 2) )"
      End
      Begin PaneConfiguration = 11
         NumPanes = 2
         Configuration = "(H (4 [60] 2))"
      End
      Begin PaneConfiguration = 12
         NumPanes = 1
         Configuration = "(H (1) )"
      End
      Begin PaneConfiguration = 13
         NumPanes = 1
         Configuration = "(V (4))"
      End
      Begin PaneConfiguration = 14
         NumPanes = 1
         Configuration = "(V (2))"
      End
      ActivePaneConfig = 0
   End
   Begin DiagramPane = 
      Begin Origin = 
         Top = 0
         Left = 0
      End
      Begin Tables = 
         Begin Table = "登录基础数据_二级菜单"
            Begin Extent = 
               Top = 9
               Left = 57
               Bottom = 201
               Right = 278
            End
            DisplayFlags = 280
            TopColumn = 10
         End
         Begin Table = "登录基础数据_角色信息"
            Begin Extent = 
               Top = 9
               Left = 316
               Bottom = 206
               Right = 549
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "登录基础数据_人员权限角色"
            Begin Extent = 
               Top = 9
               Left = 606
               Bottom = 206
               Right = 874
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "登录基础数据_人员信息"
            Begin Extent = 
               Top = 9
               Left = 931
               Bottom = 201
               Right = 1199
            End
            DisplayFlags = 280
            TopColumn = 0
         End
      End
   End
   Begin SQLPane = 
   End
   Begin DataPane = 
      Begin ParameterDefaults = ""
      End
   End
   Begin CriteriaPane = 
      Begin ColumnWidths = 11
         Column = 1440
         Alias = 900
         Table = 2970
         Output = 720
         Append = 1400
         NewValue = 1170
         SortType = 1350
         SortOrder = 1410
         GroupBy = 1350
         Filter = 1350
         Or = 1350
         Or = 1350
         Or = 1350
      End
   End
End
' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'View_账号权限信息'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPaneCount', @value=1 , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'View_账号权限信息'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPane1', @value=N'[0E232FF0-B466-11cf-A24F-00AA00A3EFFF, 1.00]
Begin DesignProperties = 
   Begin PaneConfigurations = 
      Begin PaneConfiguration = 0
         NumPanes = 4
         Configuration = "(H (1[40] 4[20] 2[20] 3) )"
      End
      Begin PaneConfiguration = 1
         NumPanes = 3
         Configuration = "(H (1 [50] 4 [25] 3))"
      End
      Begin PaneConfiguration = 2
         NumPanes = 3
         Configuration = "(H (1 [50] 2 [25] 3))"
      End
      Begin PaneConfiguration = 3
         NumPanes = 3
         Configuration = "(H (4 [30] 2 [40] 3))"
      End
      Begin PaneConfiguration = 4
         NumPanes = 2
         Configuration = "(H (1 [56] 3))"
      End
      Begin PaneConfiguration = 5
         NumPanes = 2
         Configuration = "(H (2 [66] 3))"
      End
      Begin PaneConfiguration = 6
         NumPanes = 2
         Configuration = "(H (4 [50] 3))"
      End
      Begin PaneConfiguration = 7
         NumPanes = 1
         Configuration = "(V (3))"
      End
      Begin PaneConfiguration = 8
         NumPanes = 3
         Configuration = "(H (1[56] 4[18] 2) )"
      End
      Begin PaneConfiguration = 9
         NumPanes = 2
         Configuration = "(H (1 [75] 4))"
      End
      Begin PaneConfiguration = 10
         NumPanes = 2
         Configuration = "(H (1[66] 2) )"
      End
      Begin PaneConfiguration = 11
         NumPanes = 2
         Configuration = "(H (4 [60] 2))"
      End
      Begin PaneConfiguration = 12
         NumPanes = 1
         Configuration = "(H (1) )"
      End
      Begin PaneConfiguration = 13
         NumPanes = 1
         Configuration = "(V (4))"
      End
      Begin PaneConfiguration = 14
         NumPanes = 1
         Configuration = "(V (2))"
      End
      ActivePaneConfig = 0
   End
   Begin DiagramPane = 
      Begin Origin = 
         Top = 0
         Left = 0
      End
      Begin Tables = 
         Begin Table = "MES_接口_生产计划"
            Begin Extent = 
               Top = 187
               Left = 760
               Bottom = 379
               Right = 990
            End
            DisplayFlags = 280
            TopColumn = 1
         End
         Begin Table = "MES_接口_生产计划_生产任务"
            Begin Extent = 
               Top = 38
               Left = 368
               Bottom = 375
               Right = 580
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "YL_质量检验_质检记录"
            Begin Extent = 
               Top = 9
               Left = 57
               Bottom = 371
               Right = 269
            End
            DisplayFlags = 280
            TopColumn = 2
         End
      End
   End
   Begin SQLPane = 
   End
   Begin DataPane = 
      Begin ParameterDefaults = ""
      End
   End
   Begin CriteriaPane = 
      Begin ColumnWidths = 11
         Column = 1440
         Alias = 900
         Table = 1170
         Output = 720
         Append = 1400
         NewValue = 1170
         SortType = 1350
         SortOrder = 1410
         GroupBy = 1350
         Filter = 1350
         Or = 1350
         Or = 1350
         Or = 1350
      End
   End
End
' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'View_质检明细'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPaneCount', @value=1 , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'View_质检明细'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPane1', @value=N'[0E232FF0-B466-11cf-A24F-00AA00A3EFFF, 1.00]
Begin DesignProperties = 
   Begin PaneConfigurations = 
      Begin PaneConfiguration = 0
         NumPanes = 4
         Configuration = "(H (1[40] 4[20] 2[20] 3) )"
      End
      Begin PaneConfiguration = 1
         NumPanes = 3
         Configuration = "(H (1 [50] 4 [25] 3))"
      End
      Begin PaneConfiguration = 2
         NumPanes = 3
         Configuration = "(H (1 [50] 2 [25] 3))"
      End
      Begin PaneConfiguration = 3
         NumPanes = 3
         Configuration = "(H (4 [30] 2 [40] 3))"
      End
      Begin PaneConfiguration = 4
         NumPanes = 2
         Configuration = "(H (1 [56] 3))"
      End
      Begin PaneConfiguration = 5
         NumPanes = 2
         Configuration = "(H (2 [66] 3))"
      End
      Begin PaneConfiguration = 6
         NumPanes = 2
         Configuration = "(H (4 [50] 3))"
      End
      Begin PaneConfiguration = 7
         NumPanes = 1
         Configuration = "(V (3))"
      End
      Begin PaneConfiguration = 8
         NumPanes = 3
         Configuration = "(H (1[56] 4[18] 2) )"
      End
      Begin PaneConfiguration = 9
         NumPanes = 2
         Configuration = "(H (1 [75] 4))"
      End
      Begin PaneConfiguration = 10
         NumPanes = 2
         Configuration = "(H (1[66] 2) )"
      End
      Begin PaneConfiguration = 11
         NumPanes = 2
         Configuration = "(H (4 [60] 2))"
      End
      Begin PaneConfiguration = 12
         NumPanes = 1
         Configuration = "(H (1) )"
      End
      Begin PaneConfiguration = 13
         NumPanes = 1
         Configuration = "(V (4))"
      End
      Begin PaneConfiguration = 14
         NumPanes = 1
         Configuration = "(V (2))"
      End
      ActivePaneConfig = 0
   End
   Begin DiagramPane = 
      Begin Origin = 
         Top = 0
         Left = 0
      End
      Begin Tables = 
         Begin Table = "YL_质量检验_不合格品处理"
            Begin Extent = 
               Top = 6
               Left = 38
               Bottom = 315
               Right = 199
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "YL_质量检验_不合格品处理_处理节点"
            Begin Extent = 
               Top = 6
               Left = 237
               Bottom = 299
               Right = 496
            End
            DisplayFlags = 280
            TopColumn = 0
         End
      End
   End
   Begin SQLPane = 
   End
   Begin DataPane = 
      Begin ParameterDefaults = ""
      End
      Begin ColumnWidths = 9
         Width = 284
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
      End
   End
   Begin CriteriaPane = 
      Begin ColumnWidths = 11
         Column = 1440
         Alias = 900
         Table = 1170
         Output = 720
         Append = 1400
         NewValue = 1170
         SortType = 1350
         SortOrder = 1410
         GroupBy = 1350
         Filter = 1350
         Or = 1350
         Or = 1350
         Or = 1350
      End
   End
End
' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'View_质量检验_不合格品处理'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPaneCount', @value=1 , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'View_质量检验_不合格品处理'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPane1', @value=N'[0E232FF0-B466-11cf-A24F-00AA00A3EFFF, 1.00]
Begin DesignProperties = 
   Begin PaneConfigurations = 
      Begin PaneConfiguration = 0
         NumPanes = 4
         Configuration = "(H (1[40] 4[20] 2[20] 3) )"
      End
      Begin PaneConfiguration = 1
         NumPanes = 3
         Configuration = "(H (1 [50] 4 [25] 3))"
      End
      Begin PaneConfiguration = 2
         NumPanes = 3
         Configuration = "(H (1 [50] 2 [25] 3))"
      End
      Begin PaneConfiguration = 3
         NumPanes = 3
         Configuration = "(H (4 [30] 2 [40] 3))"
      End
      Begin PaneConfiguration = 4
         NumPanes = 2
         Configuration = "(H (1 [56] 3))"
      End
      Begin PaneConfiguration = 5
         NumPanes = 2
         Configuration = "(H (2 [66] 3))"
      End
      Begin PaneConfiguration = 6
         NumPanes = 2
         Configuration = "(H (4 [50] 3))"
      End
      Begin PaneConfiguration = 7
         NumPanes = 1
         Configuration = "(V (3))"
      End
      Begin PaneConfiguration = 8
         NumPanes = 3
         Configuration = "(H (1[56] 4[18] 2) )"
      End
      Begin PaneConfiguration = 9
         NumPanes = 2
         Configuration = "(H (1 [75] 4))"
      End
      Begin PaneConfiguration = 10
         NumPanes = 2
         Configuration = "(H (1[66] 2) )"
      End
      Begin PaneConfiguration = 11
         NumPanes = 2
         Configuration = "(H (4 [60] 2))"
      End
      Begin PaneConfiguration = 12
         NumPanes = 1
         Configuration = "(H (1) )"
      End
      Begin PaneConfiguration = 13
         NumPanes = 1
         Configuration = "(V (4))"
      End
      Begin PaneConfiguration = 14
         NumPanes = 1
         Configuration = "(V (2))"
      End
      ActivePaneConfig = 0
   End
   Begin DiagramPane = 
      Begin Origin = 
         Top = 0
         Left = 0
      End
      Begin Tables = 
         Begin Table = "YL_质量检验_质检记录"
            Begin Extent = 
               Top = 9
               Left = 57
               Bottom = 201
               Right = 269
            End
            DisplayFlags = 280
            TopColumn = 0
         End
      End
   End
   Begin SQLPane = 
   End
   Begin DataPane = 
      Begin ParameterDefaults = ""
      End
   End
   Begin CriteriaPane = 
      Begin ColumnWidths = 11
         Column = 1440
         Alias = 900
         Table = 1170
         Output = 720
         Append = 1400
         NewValue = 1170
         SortType = 1350
         SortOrder = 1410
         GroupBy = 1350
         Filter = 1350
         Or = 1350
         Or = 1350
         Or = 1350
      End
   End
End
' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'View_质量检验_质检记录'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPaneCount', @value=1 , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'View_质量检验_质检记录'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPane1', @value=N'[0E232FF0-B466-11cf-A24F-00AA00A3EFFF, 1.00]
Begin DesignProperties = 
   Begin PaneConfigurations = 
      Begin PaneConfiguration = 0
         NumPanes = 4
         Configuration = "(H (1[40] 4[20] 2[20] 3) )"
      End
      Begin PaneConfiguration = 1
         NumPanes = 3
         Configuration = "(H (1 [50] 4 [25] 3))"
      End
      Begin PaneConfiguration = 2
         NumPanes = 3
         Configuration = "(H (1 [50] 2 [25] 3))"
      End
      Begin PaneConfiguration = 3
         NumPanes = 3
         Configuration = "(H (4 [30] 2 [40] 3))"
      End
      Begin PaneConfiguration = 4
         NumPanes = 2
         Configuration = "(H (1 [56] 3))"
      End
      Begin PaneConfiguration = 5
         NumPanes = 2
         Configuration = "(H (2 [66] 3))"
      End
      Begin PaneConfiguration = 6
         NumPanes = 2
         Configuration = "(H (4 [50] 3))"
      End
      Begin PaneConfiguration = 7
         NumPanes = 1
         Configuration = "(V (3))"
      End
      Begin PaneConfiguration = 8
         NumPanes = 3
         Configuration = "(H (1[56] 4[18] 2) )"
      End
      Begin PaneConfiguration = 9
         NumPanes = 2
         Configuration = "(H (1 [75] 4))"
      End
      Begin PaneConfiguration = 10
         NumPanes = 2
         Configuration = "(H (1[66] 2) )"
      End
      Begin PaneConfiguration = 11
         NumPanes = 2
         Configuration = "(H (4 [60] 2))"
      End
      Begin PaneConfiguration = 12
         NumPanes = 1
         Configuration = "(H (1) )"
      End
      Begin PaneConfiguration = 13
         NumPanes = 1
         Configuration = "(V (4))"
      End
      Begin PaneConfiguration = 14
         NumPanes = 1
         Configuration = "(V (2))"
      End
      ActivePaneConfig = 0
   End
   Begin DiagramPane = 
      Begin Origin = 
         Top = 0
         Left = 0
      End
      Begin Tables = 
         Begin Table = "YL_质量检验_质检记录"
            Begin Extent = 
               Top = 6
               Left = 38
               Bottom = 146
               Right = 199
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "MES_接口_生产计划_生产任务"
            Begin Extent = 
               Top = 6
               Left = 237
               Bottom = 146
               Right = 398
            End
            DisplayFlags = 280
            TopColumn = 0
         End
      End
   End
   Begin SQLPane = 
   End
   Begin DataPane = 
      Begin ParameterDefaults = ""
      End
   End
   Begin CriteriaPane = 
      Begin ColumnWidths = 11
         Column = 1440
         Alias = 900
         Table = 1170
         Output = 720
         Append = 1400
         NewValue = 1170
         SortType = 1350
         SortOrder = 1410
         GroupBy = 1350
         Filter = 1350
         Or = 1350
         Or = 1350
         Or = 1350
      End
   End
End
' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'View_质量检验_质检记录_外协收检'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPaneCount', @value=1 , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'View_质量检验_质检记录_外协收检'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPane1', @value=N'[0E232FF0-B466-11cf-A24F-00AA00A3EFFF, 1.00]
Begin DesignProperties = 
   Begin PaneConfigurations = 
      Begin PaneConfiguration = 0
         NumPanes = 4
         Configuration = "(H (1[40] 4[20] 2[20] 3) )"
      End
      Begin PaneConfiguration = 1
         NumPanes = 3
         Configuration = "(H (1 [50] 4 [25] 3))"
      End
      Begin PaneConfiguration = 2
         NumPanes = 3
         Configuration = "(H (1 [50] 2 [25] 3))"
      End
      Begin PaneConfiguration = 3
         NumPanes = 3
         Configuration = "(H (4 [30] 2 [40] 3))"
      End
      Begin PaneConfiguration = 4
         NumPanes = 2
         Configuration = "(H (1 [56] 3))"
      End
      Begin PaneConfiguration = 5
         NumPanes = 2
         Configuration = "(H (2 [66] 3))"
      End
      Begin PaneConfiguration = 6
         NumPanes = 2
         Configuration = "(H (4 [50] 3))"
      End
      Begin PaneConfiguration = 7
         NumPanes = 1
         Configuration = "(V (3))"
      End
      Begin PaneConfiguration = 8
         NumPanes = 3
         Configuration = "(H (1[56] 4[18] 2) )"
      End
      Begin PaneConfiguration = 9
         NumPanes = 2
         Configuration = "(H (1 [75] 4))"
      End
      Begin PaneConfiguration = 10
         NumPanes = 2
         Configuration = "(H (1[66] 2) )"
      End
      Begin PaneConfiguration = 11
         NumPanes = 2
         Configuration = "(H (4 [60] 2))"
      End
      Begin PaneConfiguration = 12
         NumPanes = 1
         Configuration = "(H (1) )"
      End
      Begin PaneConfiguration = 13
         NumPanes = 1
         Configuration = "(V (4))"
      End
      Begin PaneConfiguration = 14
         NumPanes = 1
         Configuration = "(V (2))"
      End
      ActivePaneConfig = 0
   End
   Begin DiagramPane = 
      Begin Origin = 
         Top = 0
         Left = 0
      End
      Begin Tables = 
         Begin Table = "YL_质量检验_质检记录"
            Begin Extent = 
               Top = 9
               Left = 57
               Bottom = 201
               Right = 285
            End
            DisplayFlags = 280
            TopColumn = 15
         End
      End
   End
   Begin SQLPane = 
   End
   Begin DataPane = 
      Begin ParameterDefaults = ""
      End
   End
   Begin CriteriaPane = 
      Begin ColumnWidths = 12
         Column = 1440
         Alias = 900
         Table = 1170
         Output = 720
         Append = 1400
         NewValue = 1170
         SortType = 1350
         SortOrder = 1410
         GroupBy = 1350
         Filter = 1350
         Or = 1350
         Or = 1350
         Or = 1350
      End
   End
End
' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'View_终检状态'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPaneCount', @value=1 , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'View_终检状态'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPane1', @value=N'[0E232FF0-B466-11cf-A24F-00AA00A3EFFF, 1.00]
Begin DesignProperties = 
   Begin PaneConfigurations = 
      Begin PaneConfiguration = 0
         NumPanes = 4
         Configuration = "(H (1[40] 4[20] 2[20] 3) )"
      End
      Begin PaneConfiguration = 1
         NumPanes = 3
         Configuration = "(H (1 [50] 4 [25] 3))"
      End
      Begin PaneConfiguration = 2
         NumPanes = 3
         Configuration = "(H (1 [50] 2 [25] 3))"
      End
      Begin PaneConfiguration = 3
         NumPanes = 3
         Configuration = "(H (4 [30] 2 [40] 3))"
      End
      Begin PaneConfiguration = 4
         NumPanes = 2
         Configuration = "(H (1 [56] 3))"
      End
      Begin PaneConfiguration = 5
         NumPanes = 2
         Configuration = "(H (2 [66] 3))"
      End
      Begin PaneConfiguration = 6
         NumPanes = 2
         Configuration = "(H (4 [50] 3))"
      End
      Begin PaneConfiguration = 7
         NumPanes = 1
         Configuration = "(V (3))"
      End
      Begin PaneConfiguration = 8
         NumPanes = 3
         Configuration = "(H (1[56] 4[18] 2) )"
      End
      Begin PaneConfiguration = 9
         NumPanes = 2
         Configuration = "(H (1 [75] 4))"
      End
      Begin PaneConfiguration = 10
         NumPanes = 2
         Configuration = "(H (1[66] 2) )"
      End
      Begin PaneConfiguration = 11
         NumPanes = 2
         Configuration = "(H (4 [60] 2))"
      End
      Begin PaneConfiguration = 12
         NumPanes = 1
         Configuration = "(H (1) )"
      End
      Begin PaneConfiguration = 13
         NumPanes = 1
         Configuration = "(V (4))"
      End
      Begin PaneConfiguration = 14
         NumPanes = 1
         Configuration = "(V (2))"
      End
      ActivePaneConfig = 0
   End
   Begin DiagramPane = 
      Begin Origin = 
         Top = 0
         Left = 0
      End
      Begin Tables = 
         Begin Table = "a"
            Begin Extent = 
               Top = 6
               Left = 38
               Bottom = 207
               Right = 215
            End
            DisplayFlags = 280
            TopColumn = 52
         End
         Begin Table = "b"
            Begin Extent = 
               Top = 6
               Left = 253
               Bottom = 146
               Right = 430
            End
            DisplayFlags = 280
            TopColumn = 0
         End
      End
   End
   Begin SQLPane = 
   End
   Begin DataPane = 
      Begin ParameterDefaults = ""
      End
      Begin ColumnWidths = 9
         Width = 284
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
      End
   End
   Begin CriteriaPane = 
      Begin ColumnWidths = 12
         Column = 1440
         Alias = 900
         Table = 1170
         Output = 720
         Append = 1400
         NewValue = 1170
         SortType = 1350
         SortOrder = 1410
         GroupBy = 1350
         Filter = 1350
         Or = 1350
         Or = 1350
         Or = 1350
      End
   End
End
' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'View_装配信息'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPaneCount', @value=1 , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'View_装配信息'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPane1', @value=N'[0E232FF0-B466-11cf-A24F-00AA00A3EFFF, 1.00]
Begin DesignProperties = 
   Begin PaneConfigurations = 
      Begin PaneConfiguration = 0
         NumPanes = 4
         Configuration = "(H (1[40] 4[20] 2[20] 3) )"
      End
      Begin PaneConfiguration = 1
         NumPanes = 3
         Configuration = "(H (1 [50] 4 [25] 3))"
      End
      Begin PaneConfiguration = 2
         NumPanes = 3
         Configuration = "(H (1 [50] 2 [25] 3))"
      End
      Begin PaneConfiguration = 3
         NumPanes = 3
         Configuration = "(H (4 [30] 2 [40] 3))"
      End
      Begin PaneConfiguration = 4
         NumPanes = 2
         Configuration = "(H (1 [56] 3))"
      End
      Begin PaneConfiguration = 5
         NumPanes = 2
         Configuration = "(H (2 [66] 3))"
      End
      Begin PaneConfiguration = 6
         NumPanes = 2
         Configuration = "(H (4 [50] 3))"
      End
      Begin PaneConfiguration = 7
         NumPanes = 1
         Configuration = "(V (3))"
      End
      Begin PaneConfiguration = 8
         NumPanes = 3
         Configuration = "(H (1[56] 4[18] 2) )"
      End
      Begin PaneConfiguration = 9
         NumPanes = 2
         Configuration = "(H (1 [75] 4))"
      End
      Begin PaneConfiguration = 10
         NumPanes = 2
         Configuration = "(H (1[66] 2) )"
      End
      Begin PaneConfiguration = 11
         NumPanes = 2
         Configuration = "(H (4 [60] 2))"
      End
      Begin PaneConfiguration = 12
         NumPanes = 1
         Configuration = "(H (1) )"
      End
      Begin PaneConfiguration = 13
         NumPanes = 1
         Configuration = "(V (4))"
      End
      Begin PaneConfiguration = 14
         NumPanes = 1
         Configuration = "(V (2))"
      End
      ActivePaneConfig = 0
   End
   Begin DiagramPane = 
      Begin Origin = 
         Top = 0
         Left = 0
      End
      Begin Tables = 
         Begin Table = "登录基础数据_角色信息"
            Begin Extent = 
               Top = 9
               Left = 57
               Bottom = 97
               Right = 240
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "登录基础数据_人员权限角色"
            Begin Extent = 
               Top = 9
               Left = 297
               Bottom = 188
               Right = 480
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "登录基础数据_人员信息"
            Begin Extent = 
               Top = 9
               Left = 537
               Bottom = 239
               Right = 720
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "登录基础数据_部门"
            Begin Extent = 
               Top = 167
               Left = 122
               Bottom = 329
               Right = 264
            End
            DisplayFlags = 280
            TopColumn = 0
         End
      End
   End
   Begin SQLPane = 
   End
   Begin DataPane = 
      Begin ParameterDefaults = ""
      End
      Begin ColumnWidths = 11
         Width = 284
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
      End
   End
   Begin CriteriaPane = 
      Begin ColumnWidths = 11
         Column = 1440
         Alias = 900
         Table = 1170
         Output = 720
         Append = 1400
         NewValue = 1170
         SortType = 1350
         SortOrder = 1410
         GroupBy = 1350
         Filter = 1350
         Or ' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'登录基础数据_管理人员权限视图'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPane2', @value=N'= 1350
         Or = 1350
         Or = 1350
      End
   End
End
' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'登录基础数据_管理人员权限视图'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPaneCount', @value=2 , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'登录基础数据_管理人员权限视图'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPane1', @value=N'[0E232FF0-B466-11cf-A24F-00AA00A3EFFF, 1.00]
Begin DesignProperties = 
   Begin PaneConfigurations = 
      Begin PaneConfiguration = 0
         NumPanes = 4
         Configuration = "(H (1[40] 4[20] 2[20] 3) )"
      End
      Begin PaneConfiguration = 1
         NumPanes = 3
         Configuration = "(H (1 [50] 4 [25] 3))"
      End
      Begin PaneConfiguration = 2
         NumPanes = 3
         Configuration = "(H (1 [50] 2 [25] 3))"
      End
      Begin PaneConfiguration = 3
         NumPanes = 3
         Configuration = "(H (4 [30] 2 [40] 3))"
      End
      Begin PaneConfiguration = 4
         NumPanes = 2
         Configuration = "(H (1 [56] 3))"
      End
      Begin PaneConfiguration = 5
         NumPanes = 2
         Configuration = "(H (2 [66] 3))"
      End
      Begin PaneConfiguration = 6
         NumPanes = 2
         Configuration = "(H (4 [50] 3))"
      End
      Begin PaneConfiguration = 7
         NumPanes = 1
         Configuration = "(V (3))"
      End
      Begin PaneConfiguration = 8
         NumPanes = 3
         Configuration = "(H (1[56] 4[18] 2) )"
      End
      Begin PaneConfiguration = 9
         NumPanes = 2
         Configuration = "(H (1 [75] 4))"
      End
      Begin PaneConfiguration = 10
         NumPanes = 2
         Configuration = "(H (1[66] 2) )"
      End
      Begin PaneConfiguration = 11
         NumPanes = 2
         Configuration = "(H (4 [60] 2))"
      End
      Begin PaneConfiguration = 12
         NumPanes = 1
         Configuration = "(H (1) )"
      End
      Begin PaneConfiguration = 13
         NumPanes = 1
         Configuration = "(V (4))"
      End
      Begin PaneConfiguration = 14
         NumPanes = 1
         Configuration = "(V (2))"
      End
      ActivePaneConfig = 0
   End
   Begin DiagramPane = 
      Begin Origin = 
         Top = 0
         Left = 0
      End
      Begin Tables = 
         Begin Table = "MES_接口_生产计划"
            Begin Extent = 
               Top = 282
               Left = 601
               Bottom = 474
               Right = 784
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "MES_接口_生产计划_生产任务"
            Begin Extent = 
               Top = 240
               Left = 1064
               Bottom = 432
               Right = 1276
            End
            DisplayFlags = 280
            TopColumn = 5
         End
         Begin Table = "车间生产管理工艺_零件工序_工艺库"
            Begin Extent = 
               Top = 244
               Left = 84
               Bottom = 436
               Right = 296
            End
            DisplayFlags = 280
            TopColumn = 0
         End
      End
   End
   Begin SQLPane = 
   End
   Begin DataPane = 
      Begin ParameterDefaults = ""
      End
   End
   Begin CriteriaPane = 
      Begin ColumnWidths = 11
         Column = 1440
         Alias = 900
         Table = 1170
         Output = 720
         Append = 1400
         NewValue = 1170
         SortType = 1350
         SortOrder = 1410
         GroupBy = 1350
         Filter = 1350
         Or = 1350
         Or = 1350
         Or = 1350
      End
   End
End
' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'计划任务视图'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPaneCount', @value=1 , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'计划任务视图'
GO
USE [master]
GO
ALTER DATABASE [YL_MESDB] SET  READ_WRITE 
GO
