IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID('[dbo].[mps_new_prdctg1]') AND type = 'P')
DROP PROCEDURE [dbo].[mps_new_prdctg1]
GO
-- =============================================
-- Author:<Author,,Name>
-- Create date: <Create Date,,>
-- Description:<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[mps_new_prdctg1]
-- Add the parameters for the stored procedure here
@cmpid int,
@pc_tag int,
@pc_type nvarchar(100),
@pc_level int
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED 

    -- Insert statements for procedure here
DECLARE @id int
DECLARE @order int
DECLARE @caption nvarchar(100)
SELECT TOP 1 @caption=pc_caption FROM mps_prdctg WHERE pc_cmpid=@cmpid AND pc_tag = @pc_tag ORDER BY pc_order DESC,pc_level DESC
SELECT TOP 1 @order=pc_order FROM mps_prdctg WHERE pc_cmpid = @cmpid ORDER BY pc_order DESC,pc_level DESC,pc_tag DESC
SET @order = ISNULL(@order+1,0)
print @order
SELECT TOP 1 @id=pc_id FROM mps_prdctg WHERE pc_cmpid=@cmpid AND pc_type=@pc_type AND pc_tag=@pc_tag
SET @id = ISNULL(@id , 0)
IF(@id = 0)
BEGIN
INSERT INTO mps_prdctg(pc_cmpid, pc_tag, pc_caption, pc_type, pc_full, pc_order, pc_level)
VALUES(@cmpid, @pc_tag, @caption, @pc_type, @pc_type, @order, @pc_level)
SELECT TOP 1 @id=pc_id FROM mps_prdctg WHERE pc_cmpid=@cmpid AND pc_type=@pc_type AND pc_tag=@pc_tag
SELECT *,pc_tag as datagroup FROM mps_prdctg WHERE pc_id=@id
END ELSE
BEGIN
SELECT 0 NONE WHERE 0=1
END
END