在这里,我已经使用MS SQL创建了一个简单的表
CREATE TABLE Students1 (
FirstName Nvarchar(100),
SecondName Nvarchar(100),
DOB Smalldatetime,
RegisterDate smalldatetime,
Archived int,
ArchivedDate Smalldatetime
);
Insert Into Students1(FirstName,SecondNAme,DOB,RegisterDate,Archived,ArchivedDate)
Values('James','Bike',16/04/1900, 04/07/2017,0,Null);
Insert Into Students1(FirstName,SecondNAme,DOB,RegisterDate,Archived,ArchivedDate)
Values('Adam','Bike',16/04/1901,04/07/2017,0,Null);
Insert Into Students1(FirstName,SecondNAme,DOB,RegisterDate,Archived,ArchivedDate)
Values('Chris','Bike',16/04/1902,04/09/2017,1,getdate());
Insert Into Students1(FirstName,SecondNAme,DOB,RegisterDate,Archived,ArchivedDate)
Values('Sam','Bike',16/04/1999,04/09/2017,1,getdate());
Insert Into Students1(FirstName,SecondNAme,DOB,RegisterDate,Archived,ArchivedDate)
Values('Josh','Bike',16/04/1999,04/09/2017,1,getdate());
我想对此做一个简单的select语句,根据我的局部变量的设置,在RegisterDate
或ArchivedDate
上进行过滤。
例如,我将设置以下局部变量;
@FitlerRegisterDate
@FilterArchived
如果@FilterREgisterDate
设置为1,则where子句将查看RegisterDate
列,但是如果@FilterArchived
设置为1,则where子句将查看{{1} }并且如果它们都设置为1,则应默认查看ArchivedColumn
我已经看了一段时间,看不到任何突出的内容。如果有人可以向我指出正确的方向,那就太好了。
谢谢。
答案 0 :(得分:1)
您可以使用AND
和OR
子句根据您的变量值进行过滤:
SELECT *
FROM dbo.Students1
WHERE ( @FilterArchived = 1
AND @FilterREgisterDate = 1
AND RegisterDate = @dateToFilter )
OR ( ( @FilterREgisterDate = 1
AND RegisterDate = @dateToFilter )
OR ( @FilterArchived = 1
AND ArchivedDate = @dateToFilter ) )
答案 1 :(得分:0)
类似这样的东西:
SELECT *
FROM Students1
WHERE @FilterREgisterDate = 1 AND RegisterDate = @RegisterDate
OR @FilterREgisterDate <> 1 AND @FilterArchived = 1 AND ArchivedDate = @ArchivedDate
;
?
答案 2 :(得分:0)
select * from dbo.Students1 where (@FilterArchived=1 AND @FilterREgisterDate=1) and registerdate='04/07/2017'
UNION
select * from dbo.Students1 where (@FilterArchived!=1 AND @FilterREgisterDate=1) and registerdate='04/07/2017'
UNION
select * from dbo.Students1 where (@FilterArchived=1 AND @FilterREgisterDate!=1) and archived=1