0

I have following scalar function but the problem is that it doesn't return actual result but returns a query.

Could somebody guide me on it what I am missing here or making wrong?

I have formed the following function

ALTER function test(@QueId int, @Answer varchar(250)) RETURNS VARCHAR(500) AS   
BEGIN  
   DECLARE @STR varchar(4000) 
   DECLARE @QRY AS VARCHAR(1000)

   SELECT @QRY=
     'SELECT @str = COALESCE(@str + '';'','''') + AnswerText '+  
     'FROM SurveyQuestionAnswerTypes WHERE AnswerType=(Select AnswerType From SurveyQuestions Where QuestionID=' + 
     CAST(@QueId AS VARCHAR(4)) + ')AND AnswerValue in (' + replace(@Answer,'^',',') +')'

   --EXEC sp_executesql @QRY, '@STR VARCHAR(4000)', @STR
   RETURN @QRY 
END  

Instead of returning a result it returns

SELECT @str = COALESCE(@str + ';','') + AnswerText 
FROM SurveyQuestionAnswerTypes 
WHERE AnswerType = (Select AnswerType 
                    From SurveyQuestions 
                    Where QuestionID=25)AND AnswerValue in (3,4,5,6)
4

3 回答 3

2

好吧 - 它返回查询,因为您告诉它这样做!

查看您的代码:您已经注释掉了实际执行动态 SQL ( EXEC sp_executsql .....) 的行,而是将查询 ( @QRY) 作为字符串返回:

--EXEC sp_executesql @QRY, '@STR VARCHAR(4000)', @STR
RETURN @QRY 

只需更改它以执行查询而不是返回其字符串表示形式......

于 2012-05-08T07:34:28.903 回答
0

您不能执行“exec”或“sp_executesql”,也不能在函数中执行存储过程。

你可以参考这个 博客

或者这个问题

于 2012-05-08T08:03:42.557 回答
0

试试这个语法,这可能对你有用:

Exec (@QRY)
于 2012-05-08T07:48:24.703 回答