IF EXISTS (SELECT [name] FROM sys.objects WHERE object_id = OBJECT_ID('GetTableFromDelimitedValues')) BEGIN DROP FUNCTION [GetTableFromDelimitedValues]; END GO /* Now create function */ CREATE FUNCTION [dbo].[GetTableFromDelimitedValues]( @input varchar(max), @delimiter char(1) = ',') RETURNS @Result TABLE ( Value nvarchar(4000) ) AS BEGIN .. .. .. RETURN; END
in OBJECT_ID you only need to pass the function name, not the schema. and why create it 1st, and then Alter it. Just check for the presence of the 1st one, if it exists, and then cancel the function and create your own function, as I showed above.
Also, do not add Type to where where when checking for existence, if there is another object, not a function, but any other object with the same name, it will not pick it up in your select statement, and you will end up creating a function with a name that already exists (this will cause an error).
IF you want to do it your own way, here's how you do it
IF NOT EXISTS(SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID('[GetTableFromDelimitedValues]')) BEGIN EXECUTE('CREATE FUNCTION [dbo].[GetTableFromDelimitedValues]() RETURNS @Result TABLE ( Value nvarchar(4000)) AS BEGIN RETURN END') END GO
M.Ali
source share