通过条件创建函数

时间:2017-06-07 14:58:17

标签: sql sql-server sql-server-2008 tsql sql-server-2012

我希望创建功能,如果它们不存在并在它们存在时进行更新。

但是mssql说这是函数附近的错误语法。

 IF NOT EXISTS(SELECT 1 FROM sys.objects where name='CreateJson' AND type='U' )
Begin
Create function [dbo].CreateJson
(
    @String  nvarchar(4000),
    @Param0  SQL_VARIANT = NULL
)
returns nvarchar(4000)
as
begin
    declare @Null nvarchar(4) = N'NULL';
    return  replace(@String, N'{0}', cast(isnull(@Param0, @Null) as nvarchar(4000)));
end

end
IF EXISTS(SELECT 1 FROM sys.objects where name='CreateJson' AND type='U' )
Begin

Alter function [dbo].CreateJson
(
    @String  nvarchar(4000),
    @Param0  SQL_VARIANT = NULL

)
returns nvarchar(4000)
as
begin
    declare @Null nvarchar(4) = N'NULL';
     return  replace(@String, N'{0}', cast(isnull(@Param0, @Null) as nvarchar(4000)));
       end
End
Go

如何按条件制作更新/创建功能?

1 个答案:

答案 0 :(得分:1)

有条件地放弃它可能更容易: (如Sql Server equivalent to Oracle's CREATE OR REPLACE VIEW

IF OBJECT_ID('[dbo].[CreateJson]') IS NOT NULL
DROP FUNCTION [dbo].[CreateJson]
GO
CREATE FUNCTION [dbo].[CreateJson]
AS
--