English 中文(简体)
SQL 函数, 列作为变量
原标题:SQL Function, Column as a variable

new to SQL programming, I have this function which works well:

(
@clientId AS int
)
RETURNS NVARCHAR(50)
AS
BEGIN
declare @result nvarchar(50);
declare @lastDate Date;
declare @dateBefore Date;
declare @count float;
set @count = (select  MAX(A1c)-MIN(A1c) as change from
(select A1c from 
( select top 2 * from vw_MasterView where clientId = @clientId order by vw_masterView.LastVisitDate desc  ) as vw
group by A1c) as hh);
RETURN @count
end;

由于我将重复此函数,以计算主视图中的其他列;我想将A1c改为变量,具体如下:

(
@clientId AS int,
@lab AS nvarchar(50)
)
RETURNS NVARCHAR(50)
AS
BEGIN
declare @result nvarchar(50);
declare @lastDate Date;
declare @dateBefore Date;
declare @count float;
set @count = (select  MAX(@lab)-MIN(@lab) as change from
(select @lab from 
( select top 2 * from vw_MasterView where clientId = @clientId order by vw_masterView.LastVisitDate desc  ) as vw
group by @lab) as hh);
RETURN @count
end;

我有以下错误:

Msg 164, Level 15, State 1, Procedure fn_changeA1c, Line 22
Each GROUP BY expression must contain at least one column that is not an outer reference.
Msg 8155, Level 16, State 2, Procedure fn_changeA1c, Line 22
No column name was specified for column 1 of  hh .

提前感谢。

最佳回答

您需要使用存储程序而不是函数 。

create procedure myprocedure
    @clientId AS int,
    @lab AS nvarchar(50)
    AS
BEGIN
    declare @result nvarchar(50);
    declare @lastDate Date;
    declare @dateBefore Date;
    declare @count float;
    declare @sql nvarchar(500);
    set @sql =  select  MAX(  + @lab +  )-MIN(  + @lab +  ) as change from
    (select   + @lab +   from 
    ( select top 2 * from vw_MasterView where clientId =   + convert(nvarchar, @clientId) +   order by    vw_masterView.LastVisitDate desc  ) as vw
    group by   + @lab +  ) as hh ;
    execute sp_executesql @sql;
end;
问题回答

暂无回答




相关问题
Performance impact of indexed view in MS SQL Server 2008

Does anyone have experience with using indexed view in MS SQL Server 2008? I am trying to find out how does indexed view affect performance of insert / update statements, that are adding / updating ...

Lock Escalation - What s happening here?

While altering a table (removing a column) in SQL Server 2008, I clicked the Generate Change Script button and I noticed that the change script it generated drops the column, says "go" and then runs ...

Round to nearest 5 in SQL Server

I have a Money column in my SQL Server 2008 table. In my below query how can I round it to nearest 5$ select FineAmount from tickets Thanks

热门标签