Click here to Skip to main content
15,893,337 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
i have query like which is shown below

SELECT studentname from [Student]
where [id ] in + '(' + @rollnumber + ')' .

But while executing i am getting the error as invalid syntax near @rollnumber
can u help me
Posted
Updated 20-Apr-14 19:22pm
v3
Comments
Peter Leow 21-Apr-14 1:51am    
What are the data type and value for @rollnumber?
babege 21-Apr-14 2:08am    
@roll number is data type string of values separated by comma
example
@rollnumber ='4197','4195'

1 solution

Hi,

Please try below query, Let me know if it helps.
SQL
declare @rollnumber int
declare @str nvarchar(max)
set @rollnumber =1

set @str= 'SELECT studentname from [Student] 
where [id ] in  (' + cast(@rollnumber as varchar)+ ')'

exec sp_executesql @str

Thanks,
Hitesh Varde
 
Share this answer
 
Comments
babege 21-Apr-14 2:37am    
Thanks for the reply
hi i can run this query but result set contains count=zero instead of count =1
babege 21-Apr-14 3:20am    
i am giving the input like this
@rollnumber ='4197','4195'
babege 21-Apr-14 3:51am    
incorrect syntax
4197 is in between double quote or two single quotes .
if i use two single quotes then syntax error
SET @rollnumber =' ''4197'' ' + ',' + ' ''4195'' ' error

if we use double quotes then no result instead of two

SET @rollnumber =' "4197" ' + ',' + ' "4195" ' gives zero result set instead of two
ccalma 21-Apr-14 4:56am    
I tried the code and it runs correctly.

declare @rollnumber VARCHAR(max)
declare @str nvarchar(max)
set @rollnumber ='''12345''' + ',' +'''54321'''

set @str= 'SELECT last_name from tbl_student
where [student_id ] in (' + cast(@rollnumber as varchar)+ ')'

exec sp_executesql @str
ccalma 21-Apr-14 5:00am    
yes, 2 rows has been returned.

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