【问题标题】:Issue Related to EXEC function in SQL Server与 SQL Server 中的 EXEC 函数相关的问题
【发布时间】:2012-09-10 13:57:00
【问题描述】:

我在 Varchar 变量中写了一些逻辑语句如下:

declare @P1 as varchar(max)
   set @P1 = ' (select (Convert(float,(SELECT COUNT(*) FROM  AttendanceMaster AS innerAM WHERE
                                            (AttendanceTypeId IN (SELECT  TypeId FROM AttendanceTypeMaster AS innerATM WHERE 
                                            innerAM.ParshadId = '+@ParshadId+'
                                            and (AttendanceSubjectId ='+Convert(varchar(5),@ASubjectId)+' ))) and innerAM.Attendance=''P1'''+ @innerWhereCondition +'))/6))'

现在我已经在 Exec 函数上面执行了 @P1 如下

    exec(@P1)

现在我想得到上面已经在 EXEC 函数中执行的@P1 语句的结果 并希望存储在 int 变量中。我在用户定义的函数中编写了上面的两个语句,并希望从上面的两个语句中返回 int。

我该怎么做?是否可以分配这样的结果?

Declare @result int

set @result = exec(@P1)

它抛出一个错误说:incorrect syntext near Exec

如何在 SQL Server 的用户定义函数中从 Exec 函数返回结果?

谢谢。

【问题讨论】:

    标签: c# sql-server


    【解决方案1】:

    您不能在用户定义的函数中使用EXEC。你为什么要这样做?

    【讨论】:

      【解决方案2】:

      声明@a varchar(10)

      声明@b int

      设置@a='2 * 3';

      执行('选择' + @a)

      声明@res int /???/;

      声明@sql nvarchar(max);

      设置@sql = N'SELECT @res = ' + @a;

      exec sp_executesql @sql, N'@res int OUTPUT', @res = @res OUTPUT;

      设置@b=@res

      选择@b

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-06-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多