I want to get the list of items from a database as a Java resultset. When I use the following SQL statement it works perfectly fine

SELECT First_Name FROM dbo.Names where First_Name LIKE  'A%';

However when I pass it as a parameter, it does not work
I have tried a variety of parameter constructs, but to no use.Some that I have tried are as follows

SELECT First_Name FROM dbo.Names where First_Name LIKE '%' +@letter+ '%'";
SELECT First_Name FROM dbo.Names where First_Name LIKE @letter";
SELECT First_Name FROM dbo.Names where First_Name LIKE &letter&";
SELECT First_Name FROM dbo.Names where First_Name LIKE '&letter&'";
SELECT First_Name FROM dbo.Names where First_Name LIKE +letter+";
SELECT First_Name FROM dbo.Names where First_Name LIKE '+letter+'";

Any workable solution is greatly appreciated
Thanks
Raghu

Recommended Answers

All 4 Replies

SELECT First_Name FROM dbo.Names WHERE First_Name LIKE '%' +@letter+'%'

should work for you.

SELECT First_Name FROM dbo.Names WHERE First_Name LIKE '%' +@letter+'%'

should work for you.

This did not work either.
This one throws an SQL exception "Must declare the scalar variable "@letter".

I am using MS SQL server 2008 enterprise edition.

You have to declare the variable @letter and assign it a value:

DECLARE @letter CHAR(1)
SET @letter = 'A'
SELECT First_Name FROM dbo.Names WHERE First_Name LIKE '%' + @letter + '%'

You have to declare the variable @letter and assign it a value:

DECLARE @letter CHAR(1)
SET @letter = 'A'
SELECT First_Name FROM dbo.Names WHERE First_Name LIKE '%' + @letter + '%'

Thanks for the reply. I have not yet tried your solution, but just wanted to post the solution that I was able to work out.

Following are the steps that I took to solve the problem

1. As soon as I received the request in the servlet, I concatenated
the string(letter) with %.
String let = letter+"%";

2. I passed this as the parameter.
3. The sql query was

SELECT First_Name FROM dbo.Names where First_Name LIKE '" + let+"';";
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.