SQL 中表返回函数使用 if 语句的问题
我已将我的功能简化为以下内容:
create function [dbo].[UserSuperTeams](@ProjectId int)
returns table
as
return
if @ProjectId=0
begin
select TeamId from TblTeam t
union
select 0 as TeamId
end
else
begin
select t.TeamId from TblTeam t
union
select 1 as TeamId
end;
go
我无法使其工作。似乎我有一些语法错误,但我不知道如何使其工作。有什么想法吗?
I have simplified my function to the following:
create function [dbo].[UserSuperTeams](@ProjectId int)
returns table
as
return
if @ProjectId=0
begin
select TeamId from TblTeam t
union
select 0 as TeamId
end
else
begin
select t.TeamId from TblTeam t
union
select 1 as TeamId
end;
go
I cannot make it work.. It seems I have some syntax errors, but I cannot figure out how to make it work.. Any idea?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果要在函数中使用 t-sql 代码,则需要在“returns”部分定义表,然后使用插入语句填充它:
If you are going to use t-sql code in the function, you need to define the table in the 'returns' section, then populate it with insert statements:
您必须在函数声明中使用临时名称和架构来声明表,然后在函数中将其插入:
然后类似:
这对于向表中插入多行的函数特别有效。
或者,如果您只想返回单个 SELECT 的结果,则可以使用内联返回:
You must declare the table with a temporary name and a schema in the function declaration, then insert into it in the function:
and then something like:
This works especially well for functions that insert several rows into the table.
Alternatively, if you only wish to return the results of a single
SELECT
, you can use an inline return:正如 Jeremy 所说,或者如果它确实非常像您的简化示例,您可以这样做:(
即您可能不必定义表 var/schema)
As Jeremy said, or if it really is very like your simplified example you can do:
(i.e. you may not have to define the table var/schema)
这段代码对我有用:
this code is working for me :