Tricks on how to execute string inside a function in Sql Server

后端 未结 1 1431
生来不讨喜
生来不讨喜 2020-12-20 17:25

Procedure FunctionX, Line 345

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

I get the above e

相关标签:
1条回答
  • 2020-12-20 18:09

    No there is no tricks, see The Curse and Blessings of Dynamic SQL

    Dynamic SQL in User-Defined Functions

    This very simple: you cannot use dynamic SQL from used-defined functions written in T-SQL. This is because you are not permitted 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.

    0 讨论(0)
提交回复
热议问题