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. 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".
I tried to declare the variable, but I got an error:
The variable name '@WorklistIds' has already been declared. 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. 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.