Let us take a simple example - Employee
Table with common fields such as EmployeeID
, Name
, Department
, Designation
, JoiningDate
, Salary
and Description
. You can use the following Transact-SQL CREATE TABLE
statement to create a Employee
Table within your database.
CREATE TABLE tblEmployees
(
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
)
The following INSERT
statements insert some sample records into the tblEmployee
table:
INSERT INTO tblEmployees
(EmployeeName, Department, Designation,
JoiningDate, Salary, [Description])
VALUES
('John Smith', 'IT Research', 'Research Analyst',
'02/08/2005', 23000.00, 'Analyst since 2005')
INSERT INTO tblEmployees
(EmployeeName, Department, Designation,
JoiningDate, Salary, [Description])
VALUES
('John Micheal', 'IT Operations', 'Manager',
'07/15/2007', 15000.00, NULL)
INSERT INTO tblEmployees
(EmployeeName, Department, Designation,
JoiningDate, Salary, [Description])
VALUES
('Will Smith', 'IT Support', 'Manager',
'05/20/2006', 13000.00, 'Joined last year as IT Support Manager')
Create Procedure
Create Procedure sp_EmployeeSelect
@EmployeeName NVarchar(100),
@Department NVarchar(50),
@Designation NVarchar(50),
@StartDate DateTime,
@EndDate DateTime,
@Salary Decimal(10,2)
AS
Set NoCount ON
Declare @SQLQuery AS NVarchar(4000)
Declare @ParamDefinition AS NVarchar(2000)
Set @SQLQuery = 'Select * From tblEmployees where (1=1) '
If @EmployeeName Is Not Null
Set @SQLQuery = @SQLQuery + ' And (EmployeeName = @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)'
Set @ParamDefinition = ' @EmployeeName NVarchar(100),
@Department NVarchar(50),
@Designation NVarchar(50),
@StartDate DateTime,
@EndDate DateTime,
@Salary Decimal(10,2)'
Execute sp_Executesql @SQLQuery,
@ParamDefinition,
@EmployeeName,
@Department,
@Designation,
@StartDate,
@EndDate,
@Salary
If @@ERROR <> 0 GoTo ErrorHandler
Set NoCount OFF
Return(0)
ErrorHandler:
Return(@@ERROR)
GO