我试图根据存储过程的结果运行查询

时间:2012-07-17 15:02:39

标签: sql-server-2005 select stored-procedures distinct execute

首先,这是sp_GetWorkQByUserName:

的代码
    ALTER PROCEDURE [dbo].[sp_GetWorkQByUserName]
    ( @UserName varchar(50),
      @StartDate datetime,
      @EndDate datetime )
    AS
    BEGIN
        SET NOCOUNT ON;
        SELECT DISTINCT SpotId FROM tblSpotCount WHERE StoreNum = EXECUTE sp_GetUserLocationCodes(@UserName)
        ORDER BY SpotDt ASC 
    END

我知道我的SELECT DISTINCT声明是错误的,但我这样写的是为了帮助展示我正在尝试做的事情。我想根据sp_GetUserLocationCodes的参数@UserName的结果来运行此存储过程。

据我所知,我的问题在于我如何打电话sp_GetUserLocationCodes

问题:如何根据SELECT DISTINCT存储过程的结果在tblSpotCount.SpotId上运行sp_GetUserLocationCodes查询?

1 个答案:

答案 0 :(得分:1)

您不能直接在查询中使用存储过程。但是,您可以将存储过程的结果插入临时表中并在查询中使用它:

CREATE TABLE #storeLocations
(
    -- appropriate column names and data types go here
)

INSERT INTO #storeLocations (put column list here)
EXECUTE sp_GetUserLocationCodes(@UserName)

SELECT DISTINCT SpotId
FROM tblSpotCount
WHERE EXISTS (SELECT 1
              FROM #storeLocations
              WHERE #storeLocations.StoreNum = tblSpotCount.StoreNum)
ORDER BY SpotDt ASC

DROP TABLE #storeLocations