Link to home
Start Free TrialLog in
Avatar of maqskywalker
maqskywalker

asked on

sql server filter by partial string

I'm using sql server 2008.

I'm using the Employees table from the Northwind database.

Right now i have this query where I input a comma separated string of last nams as input and it returns those employees.


Query 1

-- input is comma delimited list
DECLARE @EmployeeName varchar(2500)
SET @EmployeeName = 'Davolio,Fuller,King,'
-------------
SELECT [EmployeeID]
      ,[LastName]
      ,[FirstName]
      ,[LastName] + ' ' + [FirstName] AS FullName
FROM [Northwind].[dbo].[Employees]
WHERE( nullif( @EmployeeName, '') is null or (',' + @EmployeeName +',' LIKE '%,' + [LastName] + ',%'))
ORDER BY [LastName]

Open in new window


When I run this query i get this:

User generated image

Query 2

How do i fix the Query 2 below, so my input could be part of the last name?

So if I input this I should get the same result as Query 1.

-- input is comma delimited list of partial last names
DECLARE @EmployeeName varchar(2500)
SET @EmployeeName = 'Dav,Ful,Kin,'
-------------
SELECT [EmployeeID]
      ,[LastName]
      ,[FirstName]
      ,[LastName] + ' ' + [FirstName] AS FullName
FROM [Northwind].[dbo].[Employees]
WHERE( nullif( @EmployeeName, '') is null or (',' + @EmployeeName +',' LIKE '%,' + [LastName] + ',%'))
ORDER BY [LastName]

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of D B
D B
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Avatar of PortletPaul
PortletPaul
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of maqskywalker
maqskywalker

ASKER

Great examples! Thanks.