[英]Table-valued function that takes table as parameter and performs join
I use SQL server 2016. I want to write a function that takes a table as a parameter and then performs a join on that table with another table. 我使用SQL Server2016。我想编写一个函数,该函数将一个表作为参数,然后对该表与另一个表执行联接。 I have declared the following type:
我声明了以下类型:
CREATE TYPE WorklistTable AS TABLE (WorklistId int NOT NULL)
Then I use it in a lot of functions that do selects based on certain conditions 然后我将其用于根据特定条件进行选择的许多函数中
CREATE FUNCTION [dbo].[fnGetSomeData] (
@WorklistIds WorklistTable readonly
)
RETURNS TABLE
AS RETURN
(
select WorklistId, wlu.UserId
from @WorklistIds
join [dbo].[WorklistUser] wlu on wlu.WorklistId = @WorklistIds.worklistId
-- the rest is omitted
);
I get the following error: 我收到以下错误:
Must declare the scalar variable "@WorklistIds".
必须声明标量变量“ @WorklistIds”。
I tried to declare the variable, but I got an error: 我试图声明该变量,但出现错误:
The variable name '@WorklistIds' has already been declared.
变量名“ @WorklistIds”已经声明。 Variable names must be unique within a query batch or stored procedure.
变量名称在查询批处理或存储过程中必须唯一。
You should use aliases when you are joing to table variable. 转向表变量时,应使用别名。
CREATE FUNCTION [dbo].[fnGetSomeData] (
@WorklistIds WorklistTable readonly
)
RETURNS TABLE
AS RETURN
(
select WorklistId, wlu.UserId
from @WorklistIds t
join [dbo].[WorklistUser] wlu on wlu.WorklistId = t.worklistId
-- the rest is omitted
);
You can't directly use the @Table
name when referencing a column within a table variable. 当引用表变量中的列时,不能直接使用
@Table
名称。 You either need to alias the table or wrap it in square brackets: 您需要为表格添加别名或将其包装在方括号中:
select WorklistId, wlu.UserId
from @WorklistIds As W
join [dbo].[WorklistUser] wlu on wlu.WorklistId = W.worklistId
Or 要么
select WorklistId, wlu.UserId
from @WorklistIds
join [dbo].[WorklistUser] wlu on wlu.WorklistId = [@WorklistIds].worklistId
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.