Declare
	@ExcRun Nvarchar(Max)


;--------------------------------------------------------------------------------------------------


Declare
		@InsertOrUpdate Varchar(100) = 'Alter'
IF Not EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Fn_GetExists_Object]')
						AND type IN ( N'FN', N'IF', N'TF', N'FS', N'FT' ))
	BEGIN
		Set @InsertOrUpdate = 'Create '
	END

Set
	@ExcRun = '
		' 
	+ @InsertOrUpdate + ' 
			Function
				[dbo].[Fn_GetExists_Object]
			(
					@Name AS VARCHAR(255)
			)
			Returns Bit
			As
			Begin
				Declare 
						@Result Bit
				---------------------Exists---------------------------------------
				IF	EXISTS (SELECT 1 FROM sys.procedures AS t WHERE t.[name] = @Name) OR -----Procedures
					EXISTS (SELECT 1 FROM sys.TABLES WHERE  name=@Name) OR -------------------Table
					EXISTS (SELECT 1 FROM sys.triggers AS t WHERE t.[name] = @Name) OR  ------Trigger
					EXISTS (SELECT 1 FROM sys.types AS t WHERE t.[name] = @Name) OR ----------Type
					EXISTS (SELECT 1 FROM sys.views WHERE NAME = @Name) OR -------------------View
					EXISTS (SELECT 1 FROM sys.service_queues WHERE NAME = @Name) OR-----------Queue
					EXISTS (SELECT 1 FROM sys.services WHERE NAME = @Name) OR-----------------Service
					EXISTS (SELECT 1 FROM sys.objects WHERE  ---------------------------------Function
									object_id = OBJECT_ID(N''[''+ @Name +'']'')
									AND type IN ( N''FN'', N''IF'', N''TF'', N''FS'', N''FT'', N''D'',N''F'' ))
				BEGIN
					Set @Result = CAST(1 AS BIT)
				END
				ELSE
				BEGIN
					Set @Result = CAST(0 AS BIT)
				END

				Return @Result
			End
'

		Exec(@ExcRun)
;--------------------------------------------------------------------------------------------------
Set @InsertOrUpdate = 'Alter'
IF Not EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Fn_GetExistsColumnInTable]')
						AND type IN ( N'FN', N'IF', N'TF', N'FS', N'FT' ))
	BEGIN
		Set @InsertOrUpdate = 'Create '
	END

Set
	@ExcRun = '
'+
		@InsertOrUpdate +
'	Function
	[dbo].[Fn_GetExistsColumnInTable]
(
		@TableName As Varchar(150),
		@ColumnsName As Varchar(150)
)
Returns Bit
As
Begin
	Return
	(
		Select
				Cast(
					Case
						When Count(*) = 0 Then 0
						Else 1
					End 
				As Bit)
			From sys.columns As s
			Left Join sys.tables As t On t.[object_id] = s.[object_id]
			Where	t.[object_id] Is not Null
			And		Lower(t.[name]) Like Lower(@TableName)
			And		Lower(s.[name]) Like Lower(@ColumnsName)
	)
End
'

		Exec(@ExcRun)






;----------- truncate ----------------------
If [dbo].[Fn_GetExists_Object]('tblMediaFiles') = 1
TRUNCATE TABLE tblMediaFiles
If [dbo].[Fn_GetExists_Object]('tblTelegramFiles') = 1
TRUNCATE TABLE tblTelegramFiles
  