IF dbo.fEsisteFunzioneScalare('fEsisteCostraint') = 1 BEGIN
	DROP FUNCTION [dbo].[fEsisteCostraint]
END
|GO|
-- =============================================
-- Author:		Basty
-- Create date: 22/12/2018
-- Description:	Input Nome Costraint, resituisce true se la costraint esiste 
--		ATTENZIONE:  preferibile che la costraint sia nella forma dbo.[noemcostriant]
-- =============================================
CREATE FUNCTION [dbo].[fEsisteCostraint]
(
	 @NomeCostraint as nvarchar(200)
	,@Test as nvarchar(2)
)
RETURNS bit
AS
BEGIN

	DECLARE @Esiste BIT

	SET @Esiste = 0

	if isnull(@Test,'C') = 'C' begin	--	C = CHECK constraint
		IF OBJECT_ID(@NomeCostraint, 'C') IS NOT NULL	SET @Esiste=1
	end
	if isnull(@Test,'D') = 'D' begin	--	D = DEFAULT (constraint or stand-alone)
		IF OBJECT_ID(@NomeCostraint, 'D') IS NOT NULL	SET @Esiste=1
	end
	if isnull(@Test,'F') = 'F' begin	--	F = FOREIGN KEY constraint
		IF OBJECT_ID(@NomeCostraint, 'F') IS NOT NULL	SET @Esiste=1
	end
	if isnull(@Test,'PK') = 'PK' begin	--	PK = PRIMARY KEY constraint
		IF OBJECT_ID(@NomeCostraint, 'PK') IS NOT NULL	SET @Esiste=1
	end
	if isnull(@Test,'R') = 'R' begin	--	R = Rule (old-style, stand-alone)
		IF OBJECT_ID(@NomeCostraint, 'R') IS NOT NULL	SET @Esiste=1
	end
	if isnull(@Test,'UK') = 'UK' begin	--	UQ = UNIQUE constraint
		IF OBJECT_ID(@NomeCostraint, 'UK') IS NOT NULL	SET @Esiste=1
	end

	return @Esiste

END
|GO|

IF dbo.fEsisteFunzioneScalare('fEsisteProprietaEstesa') = 1 BEGIN
	DROP FUNCTION [dbo].[fEsisteProprietaEstesa]
END
|GO|
-- =============================================
-- Author:		Basty
-- Create date: 22/12/2018
-- Description:	Input NomeTabella e NomeProprietaEstesa, restituisce true se la proprieta esiste
-- =============================================
CREATE FUNCTION [dbo].[fEsisteProprietaEstesa]
(
	 @NomeTabella as nvarchar(200)
	,@NomeProprietaEstesa as nvarchar(200)
)
RETURNS bit
AS
BEGIN

	DECLARE @Esiste BIT

	IF EXISTS 
		(SELECT S.name as SchemaName, O.name AS ObjectName, ep.name, ep.value AS ExtendedProperty
			FROM sys.extended_properties EP
				LEFT JOIN sys.all_objects O ON ep.major_id = O.object_id 
				LEFT JOIN sys.schemas S on O.schema_id = S.schema_id
				LEFT JOIN sys.columns AS c ON ep.major_id = c.object_id AND ep.minor_id = c.column_id
			WHERE	O.name = @NomeTabella 
				AND	ep.name = @NomeProprietaEstesa
		)
		set @Esiste = 1
	ELSE
		set @Esiste = 0

	return @Esiste

END
|GO|

IF dbo.fEsisteFunzioneScalare('fnAssertMessage') = 1 BEGIN
	DROP FUNCTION [dbo].[fnAssertMessage]
END
|GO|
CREATE FUNCTION [dbo].[fnAssertMessage]
(
@Messaggio varchar(100) = ''
)
RETURNS varchar(120)
AS
BEGIN
 if @messaggio<>''
	SET @messaggio = ' - ' + @Messaggio

 RETURN  CAST(DATEPART( hh, GETDATE()) AS  varchar) + ':' +CAST(DATEPART( MI, GETDATE()) AS  varchar) + ' '+ CAST(DATEPART( SS , GETDATE()) AS  varchar) + ':' +CAST(DATEPART( MILLISECOND  , GETDATE()) AS  varchar) +@messaggio 

END
|GO|
