2016-01-16 43 views
1

我想寫一個過程到數據庫,它將返回從數據庫Tournaments加上bool參數中選擇所有數據。如果用戶已註冊,則將返回trueSQL過程選擇

電話:

exec TournamentsWithLoggedUser @user = 'asd123' 

步驟:

CREATE PROCEDURE [dbo].[TournamentsWithLoggedUser] 
    @user nvarchar(128) 
AS 
    SELECT 
     t.Id, t.Info, BIT(r.Id) 
    FROM 
     Tournaments AS t 
    LEFT JOIN 
     Registrations AS r ON t.Id = r.TournamentId 
    WHERE 
     r.UserId IS NULL OR r.UserId = @user 

    RETURN 

它的意思是這樣

1, 'some info', true //1 
2, 'some info2', false //2 
+0

我認爲它有可能以某種方式與是否存在,但我不能夠弄清楚(常規)存儲過程中的參數 –

回答

0

您正在尋找此查詢

SELECT t.id, 
     t.info, 
     Cast (CASE 
       WHEN r.userid IS NOT NULL THEN 1 
       ELSE 0 
      END AS BIT) AS IsRegistered 
FROM tournaments AS t 
     LEFT JOIN registrations AS r 
       ON t.id = r.tournamentid 
       AND r.userid = @user 
1

爲什麼不直接使用一個case語句?

CASE WHEN r.Id IS NULL THEN 0 ELSE 1 END 

將0和1更改爲任何你想要的假和真。

0

你應該清楚你實際上使用的是什麼SQL語言,但是反正可以提供一個答案:

CREATE PROCEDURE [dbo].[TournamentsWithLoggedUser] 
    @user nvarchar(128) 
AS 
BEGIN 
    SELECT t.Id, t.Info, 
     -- this works in SQL Server 
     CAST ((CASE WHEN r.UserId IS NOT NULL THEN 1 ELSE 0 END) AS BIT) AS IsRegistered 
    FROM Tournaments as t 
     LEFT JOIN Registrations as r ON t.Id = r.TournamentId 
    where r.UserId IS NULL OR r.UserId = @user 

    -- this should not be required 
    RETURN 

END

然而,與邏輯問題:

@user不能爲空,所以你的程序給人的印象是它爲單個用戶查看數據。但是,您的OR操作員允許從未註冊的用戶中選擇所有記錄,並將其與特定用戶的記錄結合在一起(如果存在)。

+0

是否爲NULLABLE。您不能將它們聲明爲「NOT NULL」,除了在指定WITH NATIVE_COMPILATION的本地編譯存儲過程中的SQL Server 2014+。 [參考文獻](https://msdn.microsoft.com/en-us/library/ms187926.aspx)。你的陳述*'@ user'不能爲空*是錯誤的。 –

1
SELECT t.Id, t.Info, 
    -- this works in SQL Server 
    CAST ((CASE WHEN r.UserId IS NOT NULL THEN 1 ELSE 0 END) AS BIT) AS IsRegistered 
FROM Tournaments as t 
    LEFT JOIN Registrations as r ON t.Id = r.TournamentId 
where (r.UserId = '' OR r.UserId = @user) 

- 我認爲這是給你的幫助...