如何在select语句中分配变量并检索其他数据?

时间:2016-02-16 18:53:29

标签: sql sql-server function tsql select

--external variables
@InputtedWardID int
as
begin
     --internal variables
     declare @wardID int 
     declare @WardName varchar(50), @NoNursesDpd int

在这里,我试图通过使用我已经创建的功能来计算在病房中部署的护士数量,从输入的病房ID中计算病房护士的数量

select @NoNursesDpd = dbo.fnc1(@InputtedWardID), 
       @wardID, @WardName

select WardID, WardName
from WardTbl
where @InputtedWardID = WardID and @WardName = WardName

end

我收到错误

  

为变量赋值的SELECT语句不能与数据检索操作结合使用。

有谁知道如何将它包装成一个select语句?

2 个答案:

答案 0 :(得分:0)

如果您不需要变量进行进一步处理,只需将其包含在结果集中:

select
    dbo.fnc1(@InputtedWardID) AS NoNursesDpd , 
    WardID, 
    WardName
from WardTbl
where @InputtedWardID = WardID and @WardName = WardName

答案 1 :(得分:0)

而不是

select @NoNursesDpd = dbo.fnc1(@InputtedWardID), 
       @wardID, @WardName

select WardID, WardName
from WardTbl
where @InputtedWardID = WardID and @WardName = WardName

end

试试这个:

select WardID, WardName, dbo.fnc1(WardID)
from WardTbl
where WardID = @InputtedWardID

end