日期:2014-05-18  浏览次数:20504 次

把表变量作为存储过程/函数的参数
可不可以把表变量作为存储过程/函数的参数用 ?
例如:
[code=SQL][/code]
create procedure Proc1
@T table
as
Select * From @T


------解决方案--------------------
参数只能代替常量,而不能用于代替表名、列名或其它数据库对象的名称
------解决方案--------------------
表变量?我没见过这么用的。

可以用实体表的表名做参数,然后存储过程里面 exec 动态拼接。
------解决方案--------------------
你可以这样,先定义一个表类型,然后在定义表变量的时候,直接使用该类型即可,例如:
创建表类型:
create type dbo.OrderTotalsByYear as table
(
orderyear int not null primary key,
qty int not null
)
定义一个表变量直接使用表类型:
declare @MyOrderTotalsByYear as dbo.OrderTotalsByYear
insert into @MyOrderTotalsByYear (orderyear,qty)
select YEAR(a.orderdate) as orderyear,SUM(b.qty) as qty from sales.Orders a inner join sales.OrderDetails b on a.orderid=b.orderid group by YEAR(a.orderdate)
select * from @MyOrderTotalsByYear
可以将@MyOrderTotalsByYear作为存储过程的参数。但是函数我没试过,另外只限于SQL2008及以上版本。