Executing dynamic SQL in a SQLServer 2005 function

后端 未结 5 719
死守一世寂寞
死守一世寂寞 2020-11-28 14:10

I will preface this question by saying, I do not think it is solvable. I also have a workaround, I can create a stored procedure with an OUTPUT to accomplish this, it is jus

相关标签:
5条回答
  • 2020-11-28 14:48

    Here is the solution

    Solution 1: Return the dynamic string from Function then

    Declare @SQLStr varchar(max) 
    DECLARE @tmptable table (<columns>)
    set @SQLStr=dbo.function(<parameters>)
    insert into @tmptable
    Exec (@SQLStr)
    
    select * from @tmptable
    

    Solution 2: call nested functions by passing parameters.

    0 讨论(0)
  • 2020-11-28 14:53

    Thank you all for the replies.

    Ron: FYI, Using that will throw an error.

    I agree that not doing what I originally intended is the best solution, I decided to go a different route. My two choices were to use sum(cast(BINARY_CHECKSUM(*) as float)) or an output parameter in a stored procedure. After unit testing speed of each, I decided to go with sum(cast(BINARY_CHECKSUM(*) as float)) to get a comparable checksum value for each table's data.

    0 讨论(0)
  • 2020-11-28 14:54

    Because functions have to play nicely with the query optimiser there are quite a few restrictions on them. This link refers to an article that discusses the limitations of UDF's in depth.

    0 讨论(0)
  • 2020-11-28 14:55

    It "ordinarily" can't be done as SQL Server treats functions as deterministic, which means that for a given set of inputs, it should always return the same outputs. A stored procedure or dynamic sql can be non-deterministic because it can change external state, such as a table, which is relied on.

    Given that in SQL server functions are always deterministic, it would be a bad idea from a future maintenance perspective to attempt to circumvent this as it could cause fairly major confusion for anyone who has to support the code in future.

    0 讨论(0)
  • 2020-11-28 15:01

    You can get around this by calling an extended stored procedure, with all the attendant hassle and security problems.

    http://decipherinfosys.wordpress.com/2008/07/16/udf-limitations-in-sql-server/

    http://decipherinfosys.wordpress.com/2007/02/27/using-getdate-in-a-udf/

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