我正在创建一个用于在表中搜索的动态 sql 查询tblEmployees
。在tblEmployees
我有一个名为的字段中,active
所以我希望如果我们将 active as 1 与其他参数一起提供,那么它应该搜索 active=1 的记录,如果我们没有为任何值提供 active 我的意思既不是 1 也不是 0 那么它应该搜索与我在查询中定义的其他参数。
CREATE TABLE tblEmployees2
(
EmployeeID SMALLINT IDENTITY(1001,1) NOT NULL,
EmployeeName NVARCHAR(100) NOT NULL,
Department NVARCHAR(50) NOT NULL,
Designation NVARCHAR(50) NOT NULL,
JoiningDate DATETIME NOT NULL,
Salary DECIMAL(10,2) NOT NULL,
[Description] NVARCHAR(1000) NULL,
active Tinyint NULL
)
INSERT INTO tblEmployees
(EmployeeName, Department, Designation,
JoiningDate, Salary, [Description],active)
VALUES
('John Smith', 'IT Research', 'Research Analyst',
'02/08/2005', 23000.00, 'Analyst since 2005',1)
INSERT INTO tblEmployees
(EmployeeName, Department, Designation,
JoiningDate, Salary, [Description],active)
VALUES
('John Micheal', 'IT Operations', 'Manager',
'07/15/2007', 15000.00, NULL,0)
INSERT INTO tblEmployees
(EmployeeName, Department, Designation,
JoiningDate, Salary, [Description],active)
VALUES
('Will Smith', 'IT Support', 'Manager',
'05/20/2006', 13000.00, 'Joined last year as IT Support Manager',1)
和动态sql——
/* Input Parameters */
Declare
@EmployeeName NVarchar(100),
@Department NVarchar(50),
@Designation NVarchar(50),
@StartDate DateTime,
@EndDate DateTime,
@Salary Decimal(10,2),
@active tinyint
set @active=1--------------if active is 1 then it returns result where active=1 and if we are not providing
--any value neither 1 nor 0 then it should return both active=1 and active=0
set @EmployeeName='joh'
/* Variable Declaration */
Declare @SQLQuery AS NVarchar(4000)
Declare @ParamDefinition AS NVarchar(2000)
/* Build the Transact-SQL String with the input parameters */
Set @SQLQuery = 'Select * From tblEmployees where (1=1) '
/* check for the condition and build the WHERE clause accordingly */
if @active=1
set @SQLQuery=@active + ' And (active = @active)'
If @EmployeeName Is Not Null
Set @SQLQuery = @SQLQuery + ' And (EmployeeName LIKE '''+ '%' + @EmployeeName + '%' + ''')'
If @Department Is Not Null
Set @SQLQuery = @SQLQuery + ' And (Department = @Department)'
If @Designation Is Not Null
Set @SQLQuery = @SQLQuery + ' And (Designation = @Designation)'
If @Salary Is Not Null
Set @SQLQuery = @SQLQuery + ' And (Salary >= @Salary)'
If (@StartDate Is Not Null) AND (@EndDate Is Not Null)
Set @SQLQuery = @SQLQuery + ' And (JoiningDate
BETWEEN @StartDate AND @EndDate)'
/* Specify Parameter Format for all input parameters included
in the stmt */
Set @ParamDefinition = ' @EmployeeName NVarchar(100),
@Department NVarchar(50),
@Designation NVarchar(50),
@StartDate DateTime,
@EndDate DateTime,
@Salary Decimal(10,2),
@active tinyint'
/* Execute the Transact-SQL String with all parameter value's
Using sp_executesql Command */
Execute sp_Executesql @SQLQuery,
@ParamDefinition,
@EmployeeName,
@Department,
@Designation,
@StartDate,
@EndDate,
@Salary,
@active
print @SQLQuery