2016-03-22 4 views
3

@feedidが1つのみのIDを返すという問題を抱えて、SQLとストア手順を発見し続けますが、どのようにidの配列を返すのですか?ストア手順のテーブルからすべてのIDを返します

declare @userId table (uid int) 
declare @feedId table (id int) 

insert into @userid(uid) 
select id 
from Users 
where name = @userName 

insert into @feedid(id) 
select feedid 
from userstofeed 
where userid in (select uid from @userId) 

select * from feed where id in (select id from @feedId) 

答えて

2

あなたがテーブル変数を使用する必要がありますこれをステップで実行します。複数の結果を持つSELECTクエリで変数を設定しても、変数には常に1つの変数しか保持されません。これをすべて1つのクエリに入れてください。

SELECT 
    F.feed_id, 
    F.other_columns -- NEVER use SELECT * 
FROM 
    Users U 
INNER JOIN UsersToFeed UTF ON UTF.userid = U.userid 
INNER JOIN Feed F ON F.feedid = UTF.feedid 
WHERE 
    U.UserName = @UserName 
1
CREATE PROC spGetItemsByUser 
(
    @userName NVARCHAR(50) 
) 
AS BEGIN 

    SET NOCOUNT ON; 

    DECLARE @userId INT 

    SELECT @userId = ID 
    FROM users 
    WHERE name = @userName 

    SELECT * 
    FROM feed f 
    WHERE EXISTS(
     SELECT * 
     FROM userstofeed uf 
     WHERE f.ID = uf.feedid 
      AND uf.userid = @userId 
    ) 

END 
2

それともシンプルで行くとプレーンの問題は、あなたがしようとしているということです

create proc spGetItemsByUser 
    @userName nvarchar(50) 
as 
begin 

    select * from Users usr 
    join UsersToFeed utf on usr.id = utf.userID 
    join feed fee on utf.feedid = fee.id 
    where usr.name = @userName 
end 
1

参加:

CREATE PROC spGetItemsByUser 
    @userName NVARCHAR(50) 
AS BEGIN 

    DECLARE @userId INT, 
      @feedId INT; 

    SELECT @userId = ID 
    FROM users 
    WHERE name = @userName 

    SELECT @feedId = feedid 
    FROM userstofeed 
    WHERE userid = @userId 

    SELECT * 
    FROM feed 
    WHERE ID = @feedId 

END 
1
CREATE PROC spGetItemsByUser 
    @userName NVARCHAR(50) 
AS BEGIN 

    DECLARE @userId INT, 
      @feedId INT; 

    SELECT @userId = ID 
    FROM users 
    WHERE name = @userName 

    SELECT * 
    FROM feed 
    WHERE ID IN (
     SELECT feedid 
     FROM userstofeed 
     WHERE userid = @userId 
    ) 

END 
関連する問題