我的 sql 函数中有以下代码:
if @max_chi > -999
begin
INSERT INTO CH_TABLE(X1, X2, VALUE)
VALUES(cur_out.sessionnumber, maxpos, max_chi)
commit
end
以下是 SQL Server 2008 查询,它给了我一个错误:
Invalid use of a side-effecting operator 'INSERT' within a function.
为什么我不被允许这样做?我可以做什么来解决这个问题?
最佳答案
您不能使用函数将数据插入基表。函数返回数据。这被列为 the very first limitation in the documentation :
User-defined functions cannot be used to perform actions that modify the database state.
“修改数据库状态”包括更改数据库中的任何数据(尽管表变量是一个明显的异常(exception),OP 在 3 年前不会关心 - 该表变量仅在函数调用期间存在,并且不会以任何方式影响基础表)。
您应该使用存储过程,而不是函数。
关于sql - 在函数内使用副作用运算符 Insert 无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18389503/