IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID('[dbo].[mps_new_docctg1]') AND type = 'P')
DROP PROCEDURE [dbo].[mps_new_docctg1]
GO
CREATE procedure [dbo].[mps_new_docctg1]
-- Add the parameters for the stored procedure here
@cmpid int,
@dc_tag int,
@dc_type nvarchar(100),
@dc_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=dc_caption FROM mps_docctg WHERE dc_cmpid=@cmpid AND dc_tag = @dc_tag ORDER BY dc_order DESC,dc_level DESC
SELECT TOP 1 @order=dc_order FROM mps_docctg WHERE dc_cmpid = @cmpid ORDER BY dc_order DESC,dc_level DESC,dc_tag DESC
SET @order = ISNULL(@order+1,0)
print @order
SELECT TOP 1 @id=dc_id FROM mps_docctg WHERE dc_cmpid=@cmpid AND dc_type=@dc_type AND dc_tag=@dc_tag
SET @id = ISNULL(@id , 0)
IF(@id = 0)
BEGIN
INSERT INTO mps_docctg(dc_cmpid, dc_tag, dc_caption, dc_type, dc_full, dc_order, dc_level)
VALUES(@cmpid, @dc_tag, @caption, @dc_type, @dc_type, @order, @dc_level)
SELECT TOP 1 @id=dc_id FROM mps_docctg WHERE dc_cmpid=@cmpid AND dc_type=@dc_type AND dc_tag=@dc_tag
SELECT *,dc_tag as datagroup FROM mps_docctg WHERE dc_id=@id
END ELSE
BEGIN
SELECT 0 NONE WHERE 0=1
END
END