2016-04-27 58 views
1

我得到'多部分標識符'Membership.Mem_Num「無法綁定。每當我嘗試執行此代碼時出錯:SQL管理工作室中的簡單存儲過程出錯

Alter Proc Procedure1 
(
@MemNum int 
) 
AS 
BEGIN 
if (@MemNum != Membership.Mem_Num) 
    Begin 
     Print 'This Member Number does not exist.' 
    End 
    Else 
    Select @MemNum AS 'MemNum', Movie.Movie_Num, Movie_Title, Movie_Year, Movie_Cost, Movie_Genre ,Price_Code 
    From Movie, Membership, Video, DetailRental, Rental 
    Where @MemNum = Membership.Mem_Num AND 
    Movie.Movie_Num = Video.Movie_Num AND 
    Video.Vid_Num = DetailRental.Vid_Num AND 
    DetailRental.Rent_Num = Rental.Rent_Num AND 
    Rental.Mem_Num = Membership.Mem_Num END 

我需要if語句來驗證表中是否存在成員編號。如果沒有,那麼代碼應該打印「成員編號不存在」。但是,我得到的問題是在if(@memnum!= Membership.mem_num)語句中。

回答

0

您正試圖在不查詢任何表的查詢的一部分中引用membership.memnum - 它無法提取該數據。如果IF語句的目的是檢查傳遞到存儲過程中@MemNum是否在成員表中存在,試試這個邏輯(您也可以使用存在的(​​),而不是計數邏輯單元):

ALTER PROC Procedure1 (@MemNum INT) 
AS 
    BEGIN 
     IF (SELECT COUNT(*) FROM membership WHERE mem_num = @MemNum) = 0 
     BEGIN 
      PRINT 'This Member Number does not exist.' 
     END 
     ELSE 
     SELECT @MemNum AS 'MemNum', 
       movie.movie_num, 
       movie_title, 
       movie_year, 
       movie_cost, 
       movie_genre, 
       price_code 
     FROM movie, 
       membership, 
       video, 
       detailrental, 
       rental 
     WHERE @MemNum = membership.mem_num 
       AND movie.movie_num = video.movie_num 
       AND video.vid_num = detailrental.vid_num 
       AND detailrental.rent_num = rental.rent_num 
       AND rental.mem_num = membership.mem_num 
    END 
+0

COUNT(*)是矯枉過正這裏。替代存在可能是'if(SELECT top(1)0 FROM membership WHERE mem_num = @MemNum)爲空' – Serg

+0

同意。頂部/存在都是更好的替代方法。 –

2

你想使用EXISTS()

if NOT EXITS(SELECT 1 FROM Membership WHERE Mem_Num = @MemNum) 
BEGIN 
-- etc 

你還應該使用現代語法的連接...它更清晰。

Select @MemNum AS 'MemNum', Movie.Movie_Num, Movie_Title, Movie_Year, Movie_Cost, Movie_Genre ,Price_Code 
From Movie 
JOIN Video ON Movie.Movie_Num = Video.Movie_Num 
JOIN DetailRental ON Video.Vid_Num = DetailRental.Vid_Num 
JOIN Rental ON DetailRental.Rent_Num = Rental.Rent_Num 
JOIN Membership ON Rental.Mem_Num = Membership.Mem_Num 
Where @MemNum = Membership.Mem_Num 
0

我需要的if語句來驗證,如果在 表

存在一個會員號你幾乎說,它在SQL

if (not exists (select null from Membership where @MemNum = Membership.Mem_Num))... 
相關問題