首页 文章

在用户定义的表函数中动态返回具有不同列的表 .

提问于
浏览
1

SQL Server存储过程和用户定义的函数之间存在一些限制 . UDF不能

  • 使用非确定性函数

  • 更改数据库的状态

  • 将消息返回给调用者

  • 有任何副作用

存储过程可以返回多个记录集,并且每次都不需要返回相同的字段 .

create proc custom.sproc_CrazyFields
          @ThisItem int
as
    begin
        if @ThisItem < 10
        begin
            select 'this' as ThisField, 'that' as ThatField, 'theOther' as theOtherField;
        end
        else
           begin
              Select 'theOther' as theOtherField, 'that' as thatField, 'this' as thisField;
           end
    end
    go
    exec custom.sproc_CrazyFields 4

    exec custom.sproc_CrazyFields 40

内联函数仅返回单个select语句 . 多语句函数必须声明返回的表 .

有没有办法通过使用UDF更改列来动态返回结果,或者这是否存在差异?

1 回答

  • 3

    抱歉,您无法在函数中使用动态SQL . 也许您可以做的是编写一个存储过程,在动态SQL中创建一个函数,调用该函数,然后删除它 . 但那么为什么不在这一点内联构建查询 .

相关问题