将函数结果分配给表变量

[英]Assign function result to a table variable


The SQL Server (2000/2005) function gets the table name and the field name as parameters and returns results from a dynamic query within the function. The results should be assigned to a Table variable which will be used further in a stored procedure. How to achieve this?

SQL Server(2000/2005)函数获取表名和字段名作为参数,并返回函数内动态查询的结果。应将结果分配给Table变量,该变量将在存储过程中进一步使用。怎么做到这一点?

I am getting error: "Only functions and extended stored procedures can be executed from within a function."

我收到错误:“只能在函数内执行函数和扩展存储过程。”

Declare @Data as table (FieldValue varchar(100))
insert into @Data select * from MyFunction ('Person.Address','AddressID')     

-- Function
Alter function MyFunction (
   @TableName varchar(100), @FieldName varchar(100) 
) returns @GetData table (
   FieldValue  varchar(100) 
) as
begin
        Declare @SQL varchar(250)
        Set @SQL = 'Select '+@FieldName+ ' from '+ @TableName
        Exec sp_executesql @SQL     
        return
end

3 个解决方案

#1


1  

I'm not sure how this works with functions, but if you have a Stored Procedure that returns a resultset, you can insert that into a table variable using INSERT EXEC statements.

我不确定它如何与函数一起工作,但是如果你有一个返回结果集的存储过程,你可以使用INSERT EXEC语句将它插入到表变量中。

INSERT @TableVariable
EXEC spYourProcedure

As long as the fields match that will work. Otherwise you can use:

只要字段匹配即可。否则你可以使用:

INSERT @TableVariable (FieldInSp1, FieldInSp2)
EXEC spYourProcedure

This way you can pass data between stored procedures. See this page on INSERT EXEC Statements for some extra information.

这样,您可以在存储过程之间传递数据。有关其他信息,请参阅INSERT EXEC语句中的此页面。

#2


2  

just to close the loop...

只是为了关闭循环......

here is the syntax for calling the function and putting those results in a table variable

这是调用函数并将这些结果放入表变量的语法

small build on @simons solution

@simons解决方案的小型构建

this ran on sql2012 and sql2014.

这是在sql2012和sql2014上运行的。

[ dont forget to close off the table statement. Easy enough to do if you have the table all on a single line. ]

[别忘了关闭表格声明。如果你把桌子全部放在一条线上就足够了。 ]

declare @t table(field1  nvarchar(100) )

insert @t select * from dbo.Cool_1Field_Function( 'parm1' ,'parm2')
select * from @t

#3


1  

You can't use "exec" in a user defined function. UDFs must be side effect free.

您不能在用户定义的函数中使用“exec”。 UDF必须是无副作用的。

智能推荐

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.itdaan.com/blog/2009/01/21/358f53eb9bc1716de827b225ec102a1d.html



 
© 2014-2019 ITdaan.com 粤ICP备14056181号  

赞助商广告