IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[foo_IdGetTemplate]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT')) DROP FUNCTION [dbo].[foo_IdGetTemplate] GO SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[foo_IdGetTemplate]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT')) BEGIN execute dbo.sp_executesql @statement = N'CREATE FUNCTION [dbo].[foo_IdGetTemplate] ( @TemplateName varchar(50) ) RETURNS int AS BEGIN return isnull((select top 1 tot.TemplateId from [dbo].[TestObjectTemplates] tot where tot.TemplateName = @TemplateName), 0) END ' END GO