sql-server - 如何在 Sql Server 函数内执行字符串的技巧

标签 sql-server function procedure

过程 FunctionX,第 345 行

Invalid use of a side-effecting operator 'EXECUTE STRING' within a function.

当我在 SQL Server 2012 中的函数内执行动态语句时,出现上述错误。 有解决方法吗?有什么技巧吗?

PS:存储过程(存储过程)太长,无法将其主体按原样插入函数内。

DECLARE @execsql NVARCHAR(2000)
Set @execsql = 'INSERT INTO @TABLE1 EXEC SPROC1 ' + @ID_COMPANY + ',' + @ID_COUNTRY 
exec (@execsql)

提前非常感谢。

此外,我还需要能够在函数内部进行删除。我知道这与函数的定义相矛盾,但我想知道是否有一些可以使用的技巧

最佳答案

不,没有任何技巧,请参阅 The Curse and Blessings of Dynamic SQL

Dynamic SQL in User-Defined Functions

This is very simple: you cannot use dynamic SQL from used-defined functions written in T-SQL. This is because you are not permitted to do anything in a UDF that could change the database state (as the UDF may be invoked as part of a query). Since you can do anything from dynamic SQL, including updates, it is obvious why dynamic SQL is not permitted.

I've seen more than one post on the newsgroups where people have been banging their head against this. But if you want to use dynamic SQL in a UDF, back out and redo your design. You have hit a roadblock, and in SQL 2000 there is no way out.

In SQL 2005 and later, you could implement your function as a CLR function. Recall that all data access from the CLR is dynamic SQL. (You are safe-guarded, so that if you perform an update operation from your function, you will get caught.) A word of warning though: data access from scalar UDFs can often give performance problems. If you say

SELECT ... FROM tbl WHERE dbo.MyUdf(somecol) = @value

and MyUdf performs data access, you have more or less created a hidden cursor.

关于sql-server - 如何在 Sql Server 函数内执行字符串的技巧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32868767/

相关文章:

oracle - 执行的过程未插入行

Mysql - 如何为存储过程返回多于 1 行

c# - SQL Server 2008 R2 上的身份验证设置是否会对性能产生影响?

c# - 编码 xml 并保存到 SQL Server

function - 我如何正确设置衰减学习率回调并将其传递给 xgboost 中的自定义函数?

php - 如何使用 PHP 创建自己的 pow 函数?

mysql - 从 mssql 服务器更新链接服务器上的 mysql 表时出错

mysql - SQL 查询以区分大小写的行

sql - 如何在SQL Server中检查回文

java - 创建对函数的引用并作为参数传递给本地方法 (Java)