如何在此存储过程中始终返回3个值?

时间:2014-04-04 20:37:01

标签: sql stored-procedures

我有一张关联表。行看起来像:id, objectID, thingID

我需要一个存储过程来执行一个返回3个值的select语句:

item1ID, item2ID, item3ID

所以查询看起来像:

SELECT TOP 3 objectID WHERE thingID = 7 -- (or something)

但是,可能并不总是返回三行。

存储过程看起来像行返回行的值是什么,但如果没有返回3,则剩下的行为零?

的示例:

数据

  • id:1,objectID:12,thingID:2
  • id:2,objectID:13,thingID:2
  • id:3,objectID:14,thingID:3
  • id:4,objectID:15,thingID:3
  • id:5,objectID:16,thingID:3

结果,其中thingID = 2

item1ID: 12, item2ID: 13, item3ID: 0

结果,其中thingID = 3

item1ID: 14, item2ID: 15, item3ID: 16

5 个答案:

答案 0 :(得分:2)

与其他答案类似,但使用sql表变量而不是临时表 当proc完成时,SQL表变量被清除。

create proc ReturnTop3
as
begin

    declare @returnTable as table (
        objectId int
    )

    declare @count int


    insert into @returnTable
        SELECT TOP 3 objectID WHERE thingID = 7

    set @count = (select COUNT(*) from @returnTable)

    while (@count < 3)
        begin
            insert into @returnTable select 0
            select @count = @count + 1
        end

    select * from @returnTable
end

答案 1 :(得分:0)

您可以创建临时表并以此方式执行

    Create table #test (Id int);

    INSERT INTO #test
    SELECT TOP 3 objectID WHERE thingID = 7



    WHILE (SELECT COUNT(1) from #test) < 3
    BEGIN
        INSERT INTO #test 
        VALUES (0)
    END

    SELECT * FROM #test

    DROP TABLE #test

答案 2 :(得分:0)

你可以做这样的事情看小提琴

http://sqlfiddle.com/#!3/ed8ca/10

select TOP 3 ID, thing
from
(
select 0 as srt,ID,thing from tbl
where thing = 2
union all
select 1 as srt,0 as ID, 0 as thing
union all
select 2 as srt,0 as ID, 0 as thing
union all
select 3 as srt,0 as ID, 0 as thing
) as t
order by srt,thing

答案 3 :(得分:0)

这样的东西?

DECLARE @InputThingID INT = 2

DECLARE @ID AS INT, @ItemID1 AS INT = 0, @ItemID2 AS INT = 0, @ItemID3 AS Int = 0
SELECT * INTO #Temp FROM MyTable WHERE ThingID=@InputThingID
SELECT TOP 1 @ID=ID, @ItemID1 = ObjectID FROM #Temp
DELETE FROM #Temp WHERE ID=@ID
SELECT TOP 1 @ID=ID, @ItemID2 = ObjectID FROM #Temp
DELETE FROM #Temp WHERE ID=@ID
SELECT TOP 1 @ID=ID, @ItemID3 = ObjectID FROM #Temp
DELETE FROM #Temp WHERE ID=@ID
SELECT @ItemID1 AS ItemID1, @ItemID2 AS ItemID2, @ItemID3 AS ItemID3
DROP TABLE #Temp

答案 4 :(得分:0)

这可能是最好的,也是最普遍的,但可能也是最困难的解决方案。需要聚合MAX函数,但不影响结果。

SELECT [1] AS Item1ID,[2] AS Item2ID, [3] AS Item3ID FROM
    (SELECT ROW_NUMBER() 
     OVER(order by id) rownum,objectId FROM data where thingId = 3) AS rows
    PIVOT(
    MAX(objectId)
    FOR rownum IN ([1],[2],[3])
    ) as piv