简体   繁体   English

来自函数的 SQL Server 默认列值

[英]SQL Server Default Column value from function

I want to set default value to Id column in Person table with a function that goes like this:我想使用如下函数将默认值设置为Person表中的Id列:

Function:功能:

IF OBJECT_ID ( 'GetLastId','FN') IS NOT NULL   
    DROP function GetLastId;  
GO  

CREATE FUNCTION [dbo].[GetLastId]
    (@TableName nvarchar(max)) 
RETURNS int
AS
BEGIN
    DECLARE @LastId int;
    DECLARE @sql nvarchar(max);

    SET @sql = 'SELECT @LastId = ISNULL(MAX(Id), 0) + 1 FROM ' + @TableName + ';'

    EXECUTE sp_executesql @sql, N'@LastId int output', @LastId = @LastId output;

    RETURN @LastId
END

and then:进而:

UPDATE Person 
SET Id = dbo.GetLastId('Person')

Running this code throws an error:运行此代码会引发错误:

Only functions and some extended stored procedures can be executed from within a function.只有函数和一些扩展存储过程可以从函数内部执行。

So how to fix this and make it work as a default value?那么如何解决这个问题并使其作为默认值工作呢?

And please do not say "Use triggers..." as I intend to use it with Entity Framework Core as default value for primary keys.并且请不要说“使用触发器...”,因为我打算将它与 Entity Framework Core 一起用作主键的默认值。

Thanks谢谢

You want a stored procedure, not a function:你想要一个存储过程,而不是一个函数:

create procedure [dbo].[GetLastId] (
    @TableName nvarchar(max),
    @LastId int output
) as
begin
   declare @sql nvarchar(max);

   set @sql = 'select @LastId = ISNULL(MAX(Id), 0) + 1 from ' + @TableName + ';'
   EXECUTE sp_executesql @sql,
                         N'@LastId int output',
                         @LastId=@LastId output;
end;

You should also use quotename() around the table name to prevent unexpected things from happening.您还应该在表名周围使用quotename()以防止发生意外情况。

Then you would call this as:然后你会称之为:

declare @lastId int;

exec dbo.GetLastId('Person', @lastid output); 

update Person
    set Id = @lastId;

You need to create stored procedure instead of function您需要创建stored procedure而不是function

create procedure [dbo].[GetLastId] (
    @TableName nvarchar(max),
    @ColumnName nvarchar(200),
    @LastId int output
) as
begin
   declare @sql nvarchar(max);

   set @sql = 'select @LastId = ISNULL(MAX('+ @ColumnName +'), 0) + 1 from ' + @TableName + ';'
   EXECUTE sp_executesql @sql,
                         N'@LastId int output',
                         @LastId=@LastId output;
end;

Then you can execute sp like below然后你可以像下面这样执行sp

declare @lastId int

exec dbo.GetLastId 'Person', 'Id' , @lastid output;
select @lastId

update Person
set Id = @lastId;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM