如何编写函数sql server 2008

时间:2014-01-10 07:38:50

标签: sql sql-server

我需要用一个参数编写函数并返回两列。我试过下面的代码

create function fun_initial_score (@phy_id varchar(20))
returns  table
as


declare @vc int;

set @vc =(select MAX(visited_count) from tbl_all_purple_flag_level )


 return (SELECT 
    pflag.Score, 
    pflag.Disability_Level

FROM tbl_phy_demographic_details as [phy] 
    inner join tbl_all_purple_flag_level as [pflag] on phy.Demographic_id=pflag.Id 
WHERE phy.Physicion_id=@phy_id
and pflag.visited_count=@vc)

我知道上面的代码显示错误,但我需要写功能与上述概念。如何写它。任何人都可以帮助我....谢谢...

1 个答案:

答案 0 :(得分:0)

如果您正在尝试编写inline table-valued function,则函数的整个主体只能是提供给return的单个select语句。但幸运的是,这似乎是可行的。我没有看到单独查询和变量保留@vc的原因:

create function fun_initial_score (@phy_id varchar(20))
returns  table
as
 return (SELECT 
    pflag.Score, 
    pflag.Disability_Level

FROM tbl_phy_demographic_details as [phy] 
    inner join tbl_all_purple_flag_level as [pflag] on phy.Demographic_id=pflag.Id 
WHERE phy.Physicion_id=@phy_id
and pflag.visited_count=(select MAX(visited_count) from tbl_all_purple_flag_level ))