如何根据其他两个字段的值从MSSQL返回一个字段

时间:2012-09-07 05:30:41

标签: c# .net sql-server database tsql

我现在是一个MySQL人,有一个我正在研究的.NET项目,无法弄清楚如何动态生成并从表中返回一个字段(列),基于两个字段表

在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

非常感谢任何帮助。

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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。

答案 2 :(得分: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

搜索ADO.NET&使用带参数的SqlCommand,可以在使用查询构造命令后传递SqlParameters。

SqlCommand.Parameters.Add();