efysis
efysis

Reputation: 136

Set my function as Default

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.

Upvotes: 1

Views: 316

Answers (2)

Andomar
Andomar

Reputation: 238176

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

Upvotes: 1

M.Ali
M.Ali

Reputation: 69554

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

Upvotes: 2

Related Questions