Use a UDF as the default value in a table column in SQL Server

独自空忆成欢 提交于 2019-12-31 01:47:54

问题


I created a scaler UDF (called sCurrentAppUser()) in SQL Server 2012 Express and I would like to use this UDF as a default value when defining a table. But every time I try, I get an error of "'sCurrentAppUser' is not a recognized built-in function name."

Since I can't post more than two links yet (reputation), I'll link to my research and references in a comment.

Here's my UDF:

ALTER FUNCTION [dbo].[sCurrentAppUser] ()
RETURNS nVarChar(128)
AS BEGIN
   DECLARE @CurrentAppUser nVarChar(128)

   IF EXISTS (SELECT 1 FROM ActiveConnections WHERE ComputerName = host_name ()) BEGIN
      SELECT   @CurrentAppUser = CONVERT (nVarChar(128), LoginUser)
      FROM     ActiveConnections
      WHERE    ComputerName = host_name ()

   END ELSE BEGIN
      SELECT   @CurrentAppUser = Convert (nVarChar(128), suser_sname ())
      WHERE    NOT EXISTS (
                  SELECT   1
                  FROM     ActiveConnections
                  WHERE    ComputerName = host_name ()
               )

   END

   RETURN @CurrentAppUser

END

And my attempt at creating the table with the default constraint on the first column:

CREATE TABLE [dbo].[Clients](
   [ModifyingUser] [nvarchar](128) NOT NULL DEFAULT sCurrentAppUser (),
   [Modification] [char](1) NULL DEFAULT 'A',
   [ModifyingHost] [nvarchar](128) NOT NULL DEFAULT host_name (),
   [ClientID] [uniqueidentifier] NOT NULL,
   [Label] [nvarchar](1024) NULL,
   CONSTRAINT [PK_Clients] PRIMARY KEY (
      [ClientID] ASC
   )
)

回答1:


You should add schema name for that function:

CREATE TABLE [dbo].[Clients](
   [ModifyingUser] [nvarchar](128) NOT NULL DEFAULT dbo.sCurrentAppUser (),
   [Modification] [char](1) NULL DEFAULT 'A',
   [ModifyingHost] [nvarchar](128) NOT NULL DEFAULT host_name (),
   [ClientID] [uniqueidentifier] NOT NULL,
   [Label] [nvarchar](1024) NULL,
   CONSTRAINT [PK_Clients] PRIMARY KEY (
      [ClientID] ASC
   )
)


来源:https://stackoverflow.com/questions/30402167/use-a-udf-as-the-default-value-in-a-table-column-in-sql-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!