如果值大于,则使用SQL Where子句

时间:2017-07-09 02:13:08

标签: sql-server where-clause

我尝试创建可选查询。我有sql proc 4 param。

ALTER PROCEDURE [dbo].[sp_OdevTümBilgiler]
@ogretmenUserId int,

@ogrenciUserId int,
@odevAdi nvarchar(50) = null,
@odevId int
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
 SELECT
  s.*,
  o.*,
  ko.*,
  ogretmenUser.UserID AS OgretmenUserId,
  ogrenciUser.UserID AS OgrenciId,
  (ogretmenUser.Name + ' ' + ogretmenUser.Surname) AS OgretmenFullName,
  (ogrenciUser.Name + ' ' + ogrenciUser.Surname) AS OgrenciFullName
FROM KullaniciOdev AS ko
INNER JOIN Odev o
  ON ko.OdevId = o.OdevId
INNER JOIN FrUser ogrenciUser
  ON ogrenciUser.UserID = ko.UserId
INNER JOIN Sinif s
  ON s.SinifId = o.ClassId
INNER JOIN FrUser ogretmenUser
  ON ogretmenUser.UserID = s.OlusturanKullaniciId
WHERE 1=1 and (@ogrenciUserId > 0 and ko.UserId = @ogrenciUserId) and
((@ogretmenUserId > 0) and s.OlusturanKullaniciId = @ogretmenUserId) and
(@odevAdi IS NOT NULL and LEN(@odevAdi) > 0 and o.OdevAdi = @odevAdi) and
(@odevId > 0 and ko.OdevId=@odevId)
  END

在我的应用程序中@ogretmenUserId默认值为-1,

@ogrenciUserId默认值为-1,

@odevAdi null,

@odevId -1

但是没有返回正确的值是查询错误?

示例我尝试:

odevId = 1且ogretmenUserId = 1027但没有返回

2 个答案:

答案 0 :(得分:3)

只有传递正确的值时,所有条件才有效。传递默认值时,它将失败。示例考虑第一个条件

(@ogrenciUserId > 0 and ko.UserId = @ogrenciUserId)

此处默认值为-1,但代码始终希望它大于0,因此当传递-1时,它将失败。与其他条件相同

您需要OR条件,每个参数都有默认值。因此,当条件将以默认值或以适当值传递时满足。

WHERE  ( @ogrenciUserId = -1 
          OR ko.userid = @ogrenciUserId ) 
       AND ( @ogretmenUserId = -1 
              OR s.olusturankullaniciid = @ogretmenUserId ) 
       AND ( @odevAdi IS NULL 
              OR o.odevadi = @odevAdi ) 
       AND ( @odevId = -1 
              OR ko.odevid = @odevId ) 

答案 1 :(得分:1)

给出以下WHERE子句:

WHERE 1=1 and 
      (@ogrenciUserId > 0 and ko.UserId = @ogrenciUserId) and
      ((@ogretmenUserId > 0) and s.OlusturanKullaniciId = @ogretmenUserId) and
      (@odevAdi IS NOT NULL and LEN(@odevAdi) > 0 and o.OdevAdi = @odevAdi) and
      (@odevId > 0 and ko.OdevId=@odevId)

中插入以下值
@odevId=1
@ogretmenUserId=1027
@ogrenciUserId default value is -1,
@odevAdi null,

WHERE子句变为:

WHERE 1=1 and 
      (-1 > 0 and ko.UserId = -1) and
      ((1027 > 0) and s.OlusturanKullaniciId = 1027) and
      (null IS NOT NULL and LEN(null) > 0 and o.OdevAdi = null) and
      (1 > 0 and ko.OdevId=1)

相当于

WHERE true and 
      false and 
      ((1027 > 0) and s.OlusturanKullaniciId = 1027) and 
      false and 
      (1 > 0 and ko.OdevId=1)

总是 false

由于输入参数始终为false,因此无论您扫描的表行的内容如何,​​WHERE子句始终返回false,因此不会选择任何行。