好吧,您应该可以使用光标来完成。这并不总是最好的方法。我假设您被迫使用现有的存储过程。
示例表
CREATE TABLE [dbo].[Products](
[ProductID] [int] IDENTITY(1,1) NOT NULL,
[ProductName] [nchar](10) NULL,
[PriorityID] [int] NULL)
CREATE TABLE [dbo].[Priority](
[PriorityID] [int] IDENTITY(1,1) NOT NULL,
[PriorityCode] [nchar](10) NULL)
(与 PK 等)。
示例存储过程:
ALTER PROCEDURE [dbo].[GetProductsBasedOnPriorityRecord]
-- Add the parameters for the stored procedure here
@PriorityID int = 0
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
SELECT * FROM Products WHERE PriorityID = @PriorityID
END
然后是这样的:
DECLARE @PriorityID INT
DECLARE @table TABLE (ProductID INT, ProductName NCHAR(10), PriorityID INT)
DECLARE cur CURSOR FOR SELECT PriorityID FROM Priority
OPEN cur
FETCH NEXT FROM cur INTO @PriorityID
WHILE @@FETCH_STATUS = 0
BEGIN
INSERT INTO @table EXEC GetProductsBasedOnPriorityRecord @PriorityID
FETCH NEXT FROM cur INTO @PriorityID
END
CLOSE cur
DEALLOCATE cur
SELECT DISTINCT * FROM @table
当然,这会对您的表格做出一些假设。另外(当然)像这样的综合示例实际上显示了一种非常简单的方法。