IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID('[dbo].[mps_new_cstctg1]') AND type = 'P')
DROP PROCEDURE [dbo].[mps_new_cstctg1]
GO
create procedure [dbo].[mps_new_cstctg1]
-- Add the parameters for the stored procedure here
@cmpid int,
@ct_tag int,
@ct_type nvarchar(100) 
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=ct_caption FROM mps_csttype WHERE ct_cmpid=@cmpid AND ct_tag = @ct_tag ORDER BY ct_order DESC 
SELECT TOP 1 @order=ct_order FROM mps_csttype WHERE ct_cmpid = @cmpid ORDER BY ct_order DESC,ct_tag DESC
SET @order = ISNULL(@order+1,0)
print @order
SELECT TOP 1 @id=ct_id FROM mps_csttype WHERE ct_cmpid=@cmpid AND ct_type=@ct_type AND ct_tag=@ct_tag
SET @id = ISNULL(@id , 0)
IF(@id = 0)
BEGIN
INSERT INTO mps_csttype(ct_cmpid, ct_tag, ct_caption, ct_type,  ct_order)
VALUES(@cmpid, @ct_tag, @caption, @ct_type,  @order)
SELECT TOP 1 @id=ct_id FROM mps_csttype WHERE ct_cmpid=@cmpid AND ct_type=@ct_type AND ct_tag=@ct_tag
SELECT *,ct_tag as datagroup FROM mps_csttype WHERE ct_id=@id
END ELSE
BEGIN
SELECT 0 NONE WHERE 0=1
END
END