我有一个程序可以根据日期获取一些数据。
ALTER PROCEDURE [dbo].[GetLatestTicketsByDate]
@Datemin datetime2,
AS
BEGIN
DECLARE @LatestTickets TABLE
(
DomainId bigint,
SoldTickets bigint
)
INSERT INTO @LatestTickets(DomainId,SoldTickets)
SELECT
DomainId, SoldTickets
FROM
DomainDetailDataHistory
WHERE
[Date] >= @Datemin
SELECT * FROM @LatestTickets
END
现在我想通过向它添加一个新的参数来使这个过程变得更聪明但是这个参数是可选的。
我的代码如下所示:
ALTER PROCEDURE [dbo].[GetLatestTicketsByDate]
@Datemin datetime2,
@Id uniqueidentifier = NULL
AS
BEGIN
DECLARE @LatestTickets TABLE
(
DomainId bigint,
SoldTickets bigint
)
IF (@Id IS NULL)
BEGIN
INSERT INTO @LatestTickets(DomainId,SoldTickets)
SELECT DomainId, SoldTickets
FROM DomainDetailDataHistory
WHERE [Date] >= @Datemin
SELECT * FROM @LatestTickets
END
ELSE
BEGIN
INSERT INTO @LatestTickets(DomainId,SoldTickets)
SELECT DomainId, SoldTickets
FROM DomainDetailDataHistory
WHERE Id = @Id AND [Date] >= @Datemin
SELECT * FROM @LatestTickets
END
END
这有效,但我不喜欢这种结构,并想知道是否有更好的方法?
我试过了:
INSERT INTO @LatestTickets(DomainId,SoldTickets)
SELECT DomainId, SoldTickets
FROM DomainDetailDataHistory
WHERE (@Id IS NOT NULL AND Id = @Id) AND [Date] >= @Datemin
SELECT * FROM @LatestTickets
但它没有用。
答案 0 :(得分:4)
使用@Id IS NULL OR Id = @Id
INSERT INTO @LatestTickets(DomainId,SoldTickets)
SELECT DomainId, SoldTickets
FROM DomainDetailDataHistory
WHERE (@Id IS NULL OR Id = @Id) AND [Date] >= @Datemin