根据sql中的条件获取信息

时间:2014-02-09 03:46:57

标签: c# asp.net sql

我正在尝试创建根据几个条件运行的SP:
我有2个表格,我加入它们之间以获取我需要的信息:
(我发送的是@LocaitonID的参数)

表1“设备”

DeviceID
Device Serial
Model
Carrier
LocationID
Active

表2“地点”

PostID
LocationName
LocationID

现在的问题是如果出现以下信息:

  1. LocationID = @ LocationID,主动=真
  2. Active = false
  3. LocationID = 0,主动=假
  4. LocationID = @ LocationID,主动=假
  5. 我怎么能用if语句做? 返回

    CREATE PROCEDURE [dbo].[GetDeviceInfo] @LocationID int = NULL AS BEGIN
    SET NOCOUNT ON;
    SELECT GAD.DeviceID,
           GAL.PostID,
           GAD.DeviceSerial,
           GAD.Model,
           GAD.Carrier,
           GAD.PhoneNumber,
           GAD.LocalName,
           GAD.Notes,
           GAD.Created
    FROM GuardAppDevices AS GAD
    JOIN GuardAppLocations AS GAL ON GAD.LocationID=GAL.LocationID
    WHERE (@LocationID = GAD.LocationID
           OR @LocationID IS NULL)
      AND GAD.Active=1
    

1 个答案:

答案 0 :(得分:0)

我不确定我是否了解整个情况,但这些标准:

  1. LocationID = @ LocationID,主动=真
  2. Active = false
  3. LocationID = 0,主动=假
  4. LocationID = @ LocationID,主动=假
  5. 可以写成SQL WHERE子句,如下所示:

    .....
    WHERE (LocationID = @LocationID AND Active = 1)
           OR (Active = 0)
           OR (LocationID = 0 AND Active = 0)
           OR (LocationID = @LocationID AND Active = 0)
    

    请注意,标准no.1和no.4可以写为单个标准:LocationID=@LocationID,假设Active字段只能包含true或false值。