在函数中使用无效的副作用运算符插入 [英] Invalid use side-effecting operator Insert within a function
问题描述
我的 sql 函数中有以下代码:
I have the following code in my sql function:
if @max_chi > -999
begin
INSERT INTO CH_TABLE(X1, X2, VALUE)
VALUES(cur_out.sessionnumber, maxpos, max_chi)
commit
end
以下是 SQL Server 2008 查询,它给了我一个错误:
The following is a SQL Server 2008 Query and it gives me an error:
在函数内无效使用副作用运算符INSERT".
Invalid use of a side-effecting operator 'INSERT' within a function.
为什么不允许我这样做?我该怎么做才能解决这个问题?
Why am I not allowed to do this? What can I do to fix this?
推荐答案
您不能使用函数将数据插入基表.函数返回数据.这被列为文档中的第一个限制:
You can't use a function to insert data into a base table. Functions return data. This is listed as the very first limitation in the documentation:
用户定义的函数不能用于执行修改数据库状态的操作.
User-defined functions cannot be used to perform actions that modify the database state.
修改数据库状态"包括更改数据库中的任何数据(尽管表变量是一个明显的例外,OP 在 3 年前不会关心 - 该表变量仅在函数调用期间有效,并且不会以任何方式影响底层表).
"Modify the database state" includes changing any data in the database (though a table variable is an obvious exception the OP wouldn't have cared about 3 years ago - this table variable only lives for the duration of the function call and does not affect the underlying tables in any way).
您应该使用存储过程,而不是函数.
You should be using a stored procedure, not a function.
这篇关于在函数中使用无效的副作用运算符插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!