如何在不使用游标的情况下为表中的每一行调用参数化存储过程

时间:2013-05-07 12:55:59

标签: sql-server stored-procedures

我的存储过程接受一个参数并返回单个值。我的要求是将存储过程调用到具有公司ID的表的每一行。我尝试了这个,但它不会起作用

SELECT CompanyID,CompanyName,EmailID,'Exec Usp_GetCount' 

+CONVERT(varchar(256),companyID) 'Employees' from Tbl_Company

由于

2 个答案:

答案 0 :(得分:4)

在您的选择中使用函数而不是存储过程 - 然后您可以执行以下操作:

SELECT CompanyId, CompanyName, dbo.GetCount(CompanyId) 'Employees'
FROM Tbl_Company
WHERE...

答案 1 :(得分:0)

试试这个 -

如果SP:

DECLARE @temp TABLE
(
      CompanyID INT
    , Cnt INT
)

DECLARE @CompanyID INT

DECLARE cur CURSOR FAST_FORWARD READ_ONLY FOR
    SELECT DISTINCT CompanyID 
    FROM dbo.Tbl_Company

OPEN cur

FETCH NEXT FROM cur INTO @CompanyID

WHILE @@FETCH_STATUS = 0 BEGIN

    DECLARE @Result INT
    EXEC @Result = dbo.Usp_GetCount CONVERT(VARCHAR(256), @CompanyID)

    INSERT INTO @temp (CompanyID, Cnt)
    SELECT @CompanyID, @Result

    FETCH NEXT FROM cur INTO @CompanyID

END

CLOSE cur
DEALLOCATE cur

SELECT 
      c.CompanyID
    , c.CompanyName
    , c.EmailID
    , Employees = t.Cnt
FROM dbo.Tbl_Company c
JOIN @temp t ON t.CompanyID = c.CompanyID

如果标量函数:

SELECT 
      c.CompanyID
    , c.CompanyName
    , c.EmailID
    , Employees = dbo.GetCount(c.CompanyID)
FROM dbo.Tbl_Company c