views:

212

answers:

2

how can i decide this problem?

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

ALTER FUNCTION [dbo].[GetDataById] ()
RETURNS INT
AS
BEGIN
  DECLARE @query NVARCHAR(500)
  DECLARE @j INT
  SET @query=N'select * from catalog'
  EXEC sp_executesql @query
  RETURN @j
END

When I try to exec this one: select dbo.GetDataById()

I get an error message:

Only functions and extended stored procedures can be executed from within a function.

A: 

You can't use dynamically-created SQL from within a function. You have to use a stored procedure for that.

But in your case I don't see why you even put your query into a variable anyway.

Joey
this is only example..i have too much long request (more than 4000 symbols), more than 2000 tables in DB, and a lot of queries are indefinitive, most of them generates on the fly..
Sergey
Well, then you need stored procedures. *Unless* you also need to join the results and use them in `SELECT` statements. Then you're either at a loss or in for some really ugly solutions.
Joey
+2  A: 

From this post by Erland Sommarskog, SQL Server MVP :

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.

CodeByMoonlight