2013-02-03 75 views
1

我在從Visual Studio中的SQL數據庫中檢索值時遇到問題。我在GUEST表中有列(GuestName,GuestPassportNo,GuestCountry,RoomID,HotelPackageID),其中HotelPackageID包含一個NULL值,其餘值都是值。當HotelPackageID爲NULL時,我總是被拋入else語句(找不到記錄)。任何人都有解決方法嗎?這裏是我的代碼:從SQL數據庫檢索空值和其他值到文本框

SqlConnection myConnect = new SqlConnection(strConnectionString); 

string strCommandText = "SELECT Guest.GuestPassportNo, 
           Guest.GuestName, 
           Guest.GuestCountry, 
           Guest.RoomID, 
           Room.RoomDescription, 
           Room.RoomPrice, 
           HotelPackages.PackageName, 
           HotelPackages.PackagePrice "; 

strCommandText += " FROM Guest, Room, HotelPackages"; 

strCommandText +=" WHERE Guest.RoomID=Room.RoomID 
        AND [email protected] 
        AND HotelPackages.PackageID=Guest.HotelPackageID 
        AND [email protected]; 

SqlCommand cmd = new SqlCommand(strCommandText, myConnect); 
cmd.Parameters.AddWithValue("@guestpno", txtPassportNo.Text); 
cmd.Parameters.AddWithValue("@guestcountry", txtGuestCountry.Text); 

try 
{ 
myConnect.Open(); 
SqlDataReader reader = cmd.ExecuteReader(); 

if(reader.Read()) 
{ 
txtGuestName.Text = reader["GuestName"].ToString(); 
txtRoomDescription.Text = reader["RoomDescription"].ToString(); 
txtRoomPrice.Text = reader["RoomPrice"].ToString(); 
txtHotelPackage.Text = reader["PackageName"].ToString(); 
txtPackagePrice.Text = reader["PackagePrice"].ToString(); 
MessageBox.Show("Guest Record Found!"); 
} 

else 
{ 
Messagebox.Show("No record Found"); 
} 

reader.Close(); 
} 

catch(Exception ex) 
{ 
MessageBox.Show(ex.message); 
} 

finally 
{ 
myConnect.Close(); 
} 

+0

我編輯了自己的冠軍。請參閱:「[應該在其標題中包含」標籤「](http://meta.stackexchange.com/questions/19190/)」,其中的共識是「不,他們不應該」。 –

回答

2

您需要更改您的查詢:

strCommandText +=" WHERE Guest.RoomID=Room.RoomID AND [email protected] AND HotelPackages.PackageID=Guest.HotelPackageID AND [email protected]; 

應該是:

strCommandText +=" WHERE Guest.RoomID=Room.RoomID AND [email protected] AND (HotelPackages.PackageID=Guest.HotelPackageID OR GUEST.HotelPackageID IS NULL) AND [email protected]; 
+0

嘿感謝您的快速響應!它應該是(HotelPackages.PackageID = Guest.HotelPackageID或GUEST.PackageID IS NULL),因爲它是guest表中的packageID可以是也可以不是null。但是當我這樣做時,我得到PackageID 1(PackageName,Packageprice)顯示在我的txtPackageName和txtPackagePrice中。 –

+0

GUEST.HotelPackageID *輸入錯誤。 –

+0

謝謝。已經修復了我的答案。在文本框中顯示內容的問題上 - 如果查詢的輸出是正確的,那麼它們應該沒問題,查詢也會返回你想要的內容?如果您在'http:// sqlfiddle.com /'上發佈了一些示例數據的鏈接,您可能會獲得更多幫助。 –