IF  EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[TRG_VALIDA_VERSAO]'))
	DROP TRIGGER [dbo].[TRG_VALIDA_VERSAO]
GO

CREATE TRIGGER [dbo].[TRG_VALIDA_VERSAO]  ON  [dbo].[PRC_SISTEMAS_CTR_VERSAO]
   FOR INSERT, UPDATE
AS 
BEGIN
	SET NOCOUNT ON;
	DECLARE @SISTEMA			AS NVARCHAR(40),
			@VERSAO 			AS NVARCHAR(40),
			@CD_USU 			AS INT,
			@MSG_ERRO 			AS NVARCHAR(50),
			@AuxQuery 			AS NVARCHAR(300),
			@SelectedVersion 	AS INT,
			@NewVersion 		AS INT,
			@NewestVersion 		AS INT;
			
	SELECT 
		@SISTEMA  = SISTEMA,
		@VERSAO  = VERSAO,
		@CD_USU	 = CD_USU
	FROM 
		INSERTED I ;
		
	IF @CD_USU =1	/* Permite o usuário 1 a fazer tudo */
	BEGIN
		RETURN;	
	END
	 
	IF @SISTEMA LIKE '%PRECIFICACAO%'
		  SET @SISTEMA ='PRECIFICACAO'
	
	SET @NewVersion = CONVERT(int, dbo.F_LIMPA_NUMEROS(@VERSAO)); /* Transforma a versão para INT */
	
	SET @AuxQuery = 'SELECT @SelectedVersion = (SELECT TOP 1 CONVERT(INT, dbo.F_LIMPA_NUMEROS(' + @SISTEMA + ')) FROM  PRC_SISTEMAS_VERSAO)'; /* Obtem a versao que atual */
	EXEC sp_executesql  @AuxQuery,
						N'@SelectedVersion INT OUTPUT', 
						@SelectedVersion = @SelectedVersion OUTPUT; 
						
	IF (@SelectedVersion <> 0)	/* Verifica se foi passada versao */
	BEGIN
		IF (@NewVersion < @SelectedVersion) /* Impede versões anteriores à informada no Config */
		BEGIN
			SET @MSG_ERRO = 'VERSAO DO SISTEMA NAO PODE SER INFERIOR A ' + CONVERT(VARCHAR,@SelectedVersion) + '.';
			RAISERROR (@MSG_ERRO,16, 1);   
			RETURN;
		END
	END
END

-------------------------
--FARMAGOI-49665
-------------------------