2012-09-07 94 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。

相关问题