简体   繁体   中英

How to set Default Value of Parameter in SQL to ALL

I have 3 parameters in my table called @StartDate , @EndDate , and @ServerName . I am wanting all 3 of these to have a default value set to ALL.

Users have the ability to choose a StartDate and an EndDate and it will return all stopped services during those dates. I am also wanting them to be able to search for a ServerName and it will return all records of that ServerName no matter when the service stopped.

My problem is searching for a server name . Right now I just have a temporary fix for the parameters which would be that the default of the @StartDate parameter is set to the beginning of the year which is a date that is before any records were logged and the @EndDate is set to the current date. So when the report is opened it shows all the records of stopped services and then the user can adjust the start and end dates as they'd like. But when I search for a ServerName I want it to just find all records of that ServerName but it still just returns ALL the records within the Start and End Dates.

Here is my query:

SELECT ServerName, ServiceName, Status, Date, Time
FROM ServicesStatus
WHERE (Date BETWEEN @StartDate AND @EndDate) OR (ServerName = @ServerName)
ORDER BY Date DESC, Time DESC, ServerName

So what I need is to get the @StartDate and @EndDate to default to all dates so when someone searches for a ServerName it will return all instances of that server in the SQL database.

I also need the same for the parameter @ServerName so when someone search for a time range, it will return with ALL the Server Names that have a stopped service during that time.

You can set your default parameter values as NULL with OR operator on where clause.

If the user didn't use any condition, then it will select all datas.

DECLARE @StartDate DATETIME = NULL
DECLARE @EndDate DATETIME  = NULL
DECLARE @ServerName VARCHAR(100) = NULL

SELECT        ServerName, ServiceName, Status, Date, Time
FROM          ServicesStatus
WHERE         
    (Date >= @StartDate OR @StartDate IS NULL) 
AND 
    (Date <= @EndDate OR @EndDate IS NULL)
OR
    (ServerName = @ServerName OR @ServerName IS NULL)
ORDER BY      Date DESC, Time DESC, ServerName

Here is a default parameter sampleFiddle

NOTE

Your default value can be other (like 'ALL' ) ​that don't have to be NULL . You can default your parameter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM