Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2000 Forums
 Transact-SQL (2000)
 Search using %

Author  Topic 

superhero
Yak Posting Veteran

52 Posts

Posted - 2007-08-13 : 09:47:30
Hi

Normally I can do a search in SQL 2000 like this.

Select username from users where username like '%john%' and I'd get results like:
Johnny
Johnnic
Johnson

Now I want to use a stored procedure looking like this:
Select username from @tablename where @fieldname like %@search%
But it says the syntax of the stored procedure is incorrect.

I'm supplying the correct table name from my application, as well as the correct field and search name. So all variables are filled. But, when I edit the Store in SQL 2000 Enterprise Manager and say "Check Syntax" it says "incorrect syntax near @search.

I want to search for all possible matches so I need to use the %.

jimf
Master Smack Fu Yak Hacker

2875 Posts

Posted - 2007-08-13 : 10:09:10
You can't use @tablename or @fieldname without using dynamic sql

declare @sql varchar(8000)

sET @sql = 'select username from '+@tablename+' where ' + @fieldname + ' like ' +'''%'+@search+'%'''
EXEC (@sql)

jim
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2007-08-14 : 01:25:20
Why do you want to pass object names as parameter?
www.sommarskog.se/dynamic_sql.com

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page
   

- Advertisement -