SQL Server Set my function as Default

zte4gxcn  于 2023-08-02  发布在  其他
关注(0)|答案(2)|浏览(114)

i have function and i want to create it as default

ALTER FUNCTION [dbo].[ModifiedBy]() 
RETURNS varchar(50) 
AS 
BEGIN 
    RETURN host_name() 
END

I want to do something like this, but it doesnt work. is it possible?

create default default_modifiedBy AS dbo.ModifiedBy()

Eror is User-defined functions, partition functions, and column references are not allowed in expressions in this context.

jchrr9hc

jchrr9hc1#

I have just tried doing this and it works fine for me:

CREATE FUNCTION [dbo].[ModifiedBy]()
RETURNS varchar(50) 
AS 
BEGIN 
    RETURN host_name() 
END 
GO

CREATE TABLE Test (
                     ID INT
                   , Hostname VARCHAR(50) DEFAULT ([dbo].[ModifiedBy]())
                 );
GO

Test

INSERT INTO dbo.Test ( ID )
VALUES  ( 1 )

SELECT * FROM  dbo.Test
6yoyoihd

6yoyoihd2#

From the MSDN page for create default :
Any constant, built-in function, or mathematical expression can be used, except those that contain alias data types. User-defined functions cannot be used

Like M.Ali writes, you can use a user-defined function if you create a column-bound default constraint with alter table ... add constraint or create table ... (col1 default dbo.MyFunc()); .

For example, for create table:
Only a constant value, such as a character string; a scalar function (either a system, user-defined, or CLR function); or NULL can be used as a default

相关问题