IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID('[dbo].[mps_new_equctg1]') AND type = 'P')
DROP PROCEDURE [dbo].[mps_new_equctg1]
GO

-- =============================================
-- Author:<Author,,Name>
-- Create date: <Create Date,,>
-- Description:<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[mps_new_equctg1]
-- Add the parameters for the stored procedure here
@cmpid int,
@ec_tag int,
@ec_type nvarchar(100),
@ec_level int
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;

    -- Insert statements for procedure here
DECLARE @id int
DECLARE @order int
DECLARE @caption nvarchar(100)
SELECT TOP 1 @caption=ec_caption FROM mps_equctg WHERE ec_cmpid=@cmpid AND ec_tag = @ec_tag ORDER BY ec_order DESC,ec_level DESC
SELECT TOP 1 @order=ec_order FROM mps_equctg WHERE ec_cmpid = @cmpid ORDER BY ec_order DESC,ec_level DESC,ec_tag DESC
SET @order = ISNULL(@order+1,0)
print @order
SELECT TOP 1 @id=ec_id FROM mps_equctg WHERE ec_cmpid=@cmpid AND ec_type=@ec_type AND ec_tag=@ec_tag
SET @id = ISNULL(@id , 0)
IF(@id = 0)
BEGIN
INSERT INTO mps_equctg(ec_cmpid, ec_tag, ec_caption, ec_type, ec_full, ec_order, ec_level)
VALUES(@cmpid, @ec_tag, @caption, @ec_type, @ec_type, @order, @ec_level)
SELECT TOP 1 @id=ec_id FROM mps_equctg WHERE ec_cmpid=@cmpid AND ec_type=@ec_type AND ec_tag=@ec_tag
SELECT *,ec_tag as datagroup FROM mps_equctg WHERE ec_id=@id
END ELSE
BEGIN
SELECT 0 NONE WHERE 0=1
END
END