1

我正在为看起来非常简单的事情而苦苦挣扎,但我没有找到任何解决方案:

  1. 我有一个名为Hotels的表,其中的第一列是 = [hotels_id] [int]
  2. 我有取决于 hotels_id值的存储过程

现在在存储过程中,我只输入了一个值 (1) 作为示例,假设我有 50 行。

有什么方法可以将表中的所有行作为参数传递给 SP 吗?我的意思是一个一个。

ALTER PROCEDURE [dbo].[spAvailableRooms]
AS
BEGIN
-- Derived tables
;with

DatesTable as
    (SELECT top (100) PERCENT Dates.dates_id as Id, Dates.dates_date as Date FROM Dates order by Dates.dates_id),

 AvaliablePerHotel as
    (SELECT top (100)percent Available_since AS Since, Available_value AS Value, Available_hotel as Hotel
                    FROM Available_rooms 
                    where  Available_hotel =1 --(HERE I NEED THE VALUES FROM TABLE)
                    ORDER BY Available_hotel, Available_since),

AllDays as
    (Select top (100)percent Id, Date, Value as Rooms, iif(value is null, '0' ,'1') as New, Hotel
        From DatesTable left JOIN AvaliablePerHotel ON Id = Since
        order by id),

AvailableGroups as
    (Select top (100)percent Hotel, Id, Date, Rooms, (sum(isnull(cast(new as float),0))over(order by id)) as RowGroup
    From AllDays
    order by id)
--

-- Query itself

Select Id, Date, iif(Rooms is null,(first_value(rooms) over (partition by RowGroup order by Id)) , Rooms) as  AvailableRooms,
        iif(Hotel is null,(first_value(Hotel) over (partition by RowGroup order by Id)) , Hotel) as  Hotel
From AvailableGroups
order by id

END
4

2 回答 2

0

您可以使用用户定义的表类型(更多信息在这里

首先,您定义一个表示要传递给存储过程的结构的类型:

CREATE TYPE [schemaName].[typeName] AS TABLE(
    [Column0] [nvarchar](255) NULL,
    [Column1] [nvarchar](255) NULL,
    [Column2] [nvarchar](255) NULL,
    [Column3] [nvarchar](255) NULL,
    [Column4] [nvarchar](255) NULL,
    [Column5] [nvarchar](255) NULL,
    [Column6] [nvarchar](255) NULL,
...
)

现在您可以创建一个存储过程,该过程将使用前面脚本定义的类型的变量作为输入:

CREATE PROCEDURE [schemaName].[SpLoad]
(
    @myRows [schemaName].[typeName] READONLY
)
    AS
    BEGIN
        INSERT INTO schemaName.DestinationTable
        SELECT * FROM @myRows
    END
于 2018-09-13T15:30:09.090 回答
0

如果您想一一传递值,那么光标是您的最佳选择

declare @id int

DECLARE cursor CURSOR FOR   
SELECT hotels_id
FROM Hotels

OPEN cursor  

FETCH NEXT FROM cursor   
INTO @id

WHILE @@FETCH_STATUS = 0  
BEGIN  

    exec [dbo].[spAvailableRooms] @id

    FETCH NEXT FROM cursor   
    INTO @id
END   
CLOSE cursor;  
DEALLOCATE cursor;  

然后在您的程序中更改传递参数

ALTER PROCEDURE [dbo].[spAvailableRooms] @id int

并用@id 替换您在代码中硬编码“1”的位置

请注意,随着表的增长,游标是单线程的,执行时间会很快增长。

于 2018-09-13T15:40:51.250 回答