CREATE TABLE Persons
(
ID int NOT NULL,
ModifiedDate datetime,
FirstName varchar(50),
LastName varchar(50),
EMail varchar(30),
PhoneNumber varchar(15),
PRIMARY KEY (ID)
);
GetX (int IDX)
如果参数为null,则返回按ModifiedDate字段降序排列的表的所有行
否则仅返回与ID匹配的行
答案 0 :(得分:3)
您想要的是“全部捕获”查询。对于SQL Server,可以通过两种方法完成。 Aaron Bertrand writes about it here.
create procedure GetX (@IDX int = null)
as
select
ID
,ModifiedDate
,FirstName
,LastName
,EMail
,PhoneNumber
from Persons
where @IDX is null or ID = @IDX
order by ModifiedDate desc
然后
exec GetX @IDX = 4;
exec GetX @IDX = null;