Click here to Skip to main content
15,918,808 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
How To use variables in where,Orderby Classes & Like Conduction in SqlServer 2005

i mention my code in below lines.. but MyCode Not Returning any Values
@target varchar(30),
@prefixText varchar(100)

As
Begin


SELECT Top 10 ad.Doctor_Code, ad.DoctorName, Admin_Doctor_Timing.AvailabilityStatus, Admin_Department.Department_Name,Admin_Company_Master.CompanyOrBranchName AS Branch FROM Admin_Department INNER JOIN Admin_Doctor AS ad 
	ON Admin_Department.Department_Code = ad.Department INNER JOIN 
	Admin_Company_Master ON ad.Branch = Admin_Company_Master.Branch_Code LEFT OUTER JOIN 
	Admin_Doctor_Timing ON ad.Doctor_Code = Admin_Doctor_Timing.Doctor_Code 
	where @target Like @prefixText +'%' ORDER BY DoctorName Asc


End 

End 
Posted

Now i got solution from Mika Wendelius & i applyed his suggestion now it's working fine

my code :

 (
@target varchar(30),
@prefixText varchar(100)
)

as
begin
	declare @sqry as varchar(1000)
set @sqry='SELECT Top 10 ad.Doctor_Code, ad.DoctorName, Admin_Doctor_Timing.AvailabilityStatus, Admin_Department.Department_Name,Admin_Company_Master.CompanyOrBranchName AS Branch FROM Admin_Department INNER JOIN Admin_Doctor AS ad 
	ON Admin_Department.Department_Code = ad.Department INNER JOIN 
	Admin_Company_Master ON ad.Branch = Admin_Company_Master.Branch_Code LEFT OUTER JOIN 
	Admin_Doctor_Timing ON ad.Doctor_Code = Admin_Doctor_Timing.Doctor_Code 
	where '  + @target+ ' Like ''' +@prefixText +'%'' ORDER BY ' + @target+ ' Asc'
--print @Sqry
Exec(@sqry) 
end
 
Share this answer
 
v2
In the where condition, use column names. You cannot vary a column using a variable. So this:
SQL
where @target Like @prefixText +'%' ORDER BY DoctorName Asc

should be like
SQL
where columnname Like @prefixText ORDER BY DoctorName Asc


Also depending where the variable prefixtext is coming, add the % to the end of the variable or let the user add it, don't put it in the statement directly. So before the select you could have something like:
SQL
set @prefixtext = @prefixtext + '%'


If you want to vary the statement using variables you should put the SQL text into a string variable and then use the target variable to add relevant column. Like:
SQL
SET @sqlText = 'SELECT TOP...WKERE ' @target + ' LIKE...'

And then use EXECUTE[^] to run the statement.
 
Share this answer
 
Comments
sathishreddy A 2-Apr-11 2:49am    
ya gentle man Ur suggestion is working ...thank u
Wendelius 2-Apr-11 3:18am    
You're welcome, glad it helped :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900