IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID('[dbo].[mps_new_cstctg]') AND type = 'P')
DROP PROCEDURE [dbo].[mps_new_cstctg]
GO
create procedure [dbo].[mps_new_cstctg]
-- Add the parameters for the stored procedure here
@cmpid int,
@ct_caption nvarchar(50)
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 @tag int
SELECT TOP 1 @tag=ct_tag FROM mps_csttype GROUP BY ct_tag ORDER BY ct_tag DESC 
SET @tag = ISNULL(@tag+1,0)
SELECT TOP 1 @id=ct_id FROM mps_csttype WHERE ct_cmpid=@cmpid AND ct_caption=@ct_caption
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, @tag, @ct_caption, 'new content', 999)
SELECT TOP 1 @id=ct_id FROM mps_csttype WHERE ct_cmpid=@cmpid AND ct_caption=@ct_caption
SELECT * FROM mps_csttype WHERE ct_id=@id
END ELSE
BEGIN
SELECT 0 NONE WHERE 0=1
END
set nocount off
END