2012-09-07 153 views
1

我現在是一個MySQL人,並且有一個.NET項目,我正在處理並無法弄清楚如何動態生成並返回基於表中的兩個字段,來自表的字段(列)。如何從MSSQL基於其他兩個字段的值返回一個字段

在Units表中有兩個字段bRentable和bRented,如果bRentable和bRented等於零,我需要返回一個名爲reserved的字段。

這裏是SQL我到目前爲止

/* Units Query */ 
SELECT Units.UnitID, Units.dcWidth, Units.dcLength, Units.dcPushRate, 
     Units.dcStdRate, Units.UnitTypeID, UnitTypes.sTypeName, Units.bRentable  
FROM Units 
INNER JOIN UnitTypes ON Units.UnitTypeID = UnitTypes.UnitTypeID 

任何幫助將不勝感激。

+0

不知道你想達到什麼。更多的解釋將有助於理解你的問題。 – pramodtech

+0

基本上在我的SQL查詢中,我需要檢查bRentable = 0和bRented = 0,如果是,則返回一列bReserved = 1. –

+0

'reserved'字段將等於什麼?如果條件'bRentable = 0 AND bRented = 0'爲假,它會被返回嗎? – Dennis

回答

1

您可以添加以下的另一列到你的SELECT語句:

(cast case 
when (bRentable = 0 and bRented = 0) then 1 
else 0 
end as bit) as reserved 

編輯:基於OP的更新評論:

SELECT Units.UnitID, Units.dcWidth, Units.dcLength, Units.dcPushRate, 
     Units.dcStdRate, Units.UnitTypeID, UnitTypes.sTypeName, Units.bRentable,(cast case 
    when (bRentable = 0 and bRented = 0) then 1 
    else 0 
    end as bit) as reserved 
FROM Units 
INNER JOIN UnitTypes ON Units.UnitTypeID = UnitTypes.UnitTypeID 
+0

在我的查詢中,這會去哪裏? –

+0

@CarlWeis更新了查詢。 – danish

+0

謝謝你的工作就像一個魅力。 :) –

0

如果你想存儲過程或用戶定義的函數,下面的查詢將有所幫助。

DECLARE @Rentable BIT 
DECLARE @Rented BIT 
DECLARE @Reserved BIT 

SELECT @Rentable = U.bRentable, @Rented = U.bRented 
    FROM UNITS U INNER JOIN UnitTypes UT ON U.UnitTypeId = UT.UnitTypeId 

IF(@Rentable = 0 AND @Rented = 0) 
BEGIN 
    SET @Reserved = 0 
END 
ELSE 
BEGIN 
    SET @Reserved = 1 
END 

RETURN @Reserved // OR SELECT @Reserved 

搜索使用SqlCommand時使用的參數ADO.NET &,你可以用你的查詢框的命令後,通過SqlParameters。

SqlCommand.Parameters.Add(); 
1
SELECT Units.UnitID, Units.dcWidth, Units.dcLength, Units.dcPushRate, 
     Units.dcStdRate, Units.UnitTypeID, UnitTypes.sTypeName, Units.bRentable, 
     CASE When (Units.bRentable = 0 and Units.bRented = 0) then 1 else 0 end as reserved 
FROM Units 
INNER JOIN UnitTypes ON Units.UnitTypeID = UnitTypes.UnitTypeID 

此查詢中後,你的函數或sproc,你可以只檢查保留字段的值。如果它返回1。

相關問題