---How to search using all or partial columns without Dynamic SQL
CREATE TABLE dbo.WebContacts
(
ContactID int identity primary key,
FirstName varchar(30),
LastName varchar(30),
Address varchar(100),
City varchar(50),
State char(2),
Zip varchar(10),
Phone varchar(12),
Email varchar(50)
)
-- Load Sample Data
INSERT INTO dbo.WebContacts
VALUES ('Donald', 'Duck', '123 Main St.', 'Disney Land', 'FL',
'32247', '123-456-7890', 'donaldduck@disney.com')
INSERT INTO dbo.WebContacts
VALUES ('Daisy', 'Duck', '123 Main St.', 'Disney Land', 'FL',
'32247', '222-456-7890', 'daisyduck@disney.com')
INSERT INTO dbo.WebContacts
VALUES ('Uncle', 'Scrooge', '123 Main St.', 'Disney Land', 'FL',
'32247', '407-456-7890', 'unclescrooge@disney.com')
INSERT INTO dbo.WebContacts
VALUES ('Mickey', 'Mouse', '123 Main St.', 'Disney Land', 'FL',
'32247', '407-456-7890', 'mickeymouse@disney.com')
go
select * from WebContacts
go
CREATE PROCEDURE [dbo].[usp_SearchWebContacts]
(
@FirstName varchar(30) = null,
@LastName varchar(30) = null,
@Address varchar(100) = null,
@City varchar(50) = null,
@State char(2) = null,
@Zip varchar(10) = null,
@Phone varchar(12) = null,
@Email varchar(50) = null,
@Generic varchar(100) = null
)
AS
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
/*
usp_searchwebcontacts @City='Dis'
*/
create procedure usp_searchwebcontacts
(@FirstName varchar(100) = null,
@LastName varchar(100) = null,
@Address varchar(100) = null,
@city varchar(50) = null,
@State varchar(10) = null,
@zip varchar(10) = null,
@phone varchar(12) = null,
@email varchar(50) = null,
@Generic varchar(100) = null
)
as
set nocount on
select ContactID, FirstName, LastName, Address, City, State, Zip, Phone, Email from WebContacts
where ((@FirstName IS NULL OR FirstName like '%' + @FirstName+'%')
AND (@LastName IS NULL OR LastName like '%' + @LastName+'%')
AND (@Address IS NULL OR Address like '%' + @Address+'%')
AND (@city IS NULL OR city like '%' + @city+'%')
AND (@State IS NULL OR State LIKE '%'+@State+'%')
AND (@Zip IS NULL OR Zip LIKE '%'+@Zip+'%')
AND (@Phone IS NULL OR Phone LIKE '%'+@Phone+'%')
AND (@Email IS NULL OR Email LIKE '%'+@Email+'%'))
AND (@generic IS NULL
OR (FirstName LIKE '%'+@Generic+'%'
OR LastName LIKE '%'+@Generic+'%'
OR Address LIKE '%'+@Generic+'%'
OR City LIKE '%'+@Generic+'%'
OR State LIKE '%'+@Generic+'%'
OR Zip LIKE '%'+@Generic+'%'
OR Phone LIKE '%'+@Generic+'%'
OR Email LIKE '%'+@Generic+'%'))
Happy Coding!!!!!
No comments:
Post a Comment