IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID('[dbo].[mps_new_title]') AND type = 'P')
DROP PROCEDURE [dbo].[mps_new_title]
GO
CREATE procedure [dbo].[mps_new_title]
-- Add the parameters for the stored procedure here
@cmpid int,
@ot_code varchar(20),
@ot_title nvarchar(50),
@ot_gradecaption nvarchar(50)
AS
BEGIN
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
-- 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
SELECT TOP 1 @order=ot_order FROM mps_title WHERE ot_cmpid = @cmpid ORDER BY ot_order desc,ot_level desc
SET @order = ISNULL(@order+1,0)
SELECT TOP 1 @id=ot_id FROM mps_title WHERE ot_cmpid=@cmpid AND ot_code=@ot_code AND ot_title=@ot_title AND ot_gradecaption=@ot_gradecaption
SET @id = ISNULL(@id , 0)
IF(@id = 0)
BEGIN
DECLARE @ot_grade int
SELECT @ot_grade = tg_grade FROM mps_title_grade WHERE tg_caption = @ot_gradecaption
SET @ot_grade = ISNULL(@ot_grade,'0')
INSERT INTO mps_title(ot_cmpid, ot_code, ot_title, ot_grade, ot_gradecaption,ot_display,ot_order)
VALUES(@cmpid, @ot_code, @ot_title, @ot_grade, @ot_gradecaption,@ot_title,@order)
SELECT TOP 1 @id=ot_id FROM mps_title WHERE ot_cmpid=@cmpid AND ot_code=@ot_code AND ot_title=@ot_title AND ot_gradecaption=@ot_gradecaption
SELECT * FROM mps_title WHERE ot_id=@id
END ELSE
BEGIN
SELECT 0 NONE WHERE 0=1
END
END