Click here to Skip to main content
15,904,494 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
SQL
declare @ColumnName varchar
declare @Value varchar

set @ColumnName='Some Column Name'
set @Value='Some value'
select * from Table_Name Where @ColumnName=@Value


I am creating a stored procedure as above. So that I can pass the column name and also value from the code behind.

Before that I made a test:

1. Declared the column name and value
2. Set both Column name and value as in database
3. Selected from table name as above

I am not getting errors but No data is retrieved.

But the column name and value are correct.
Posted
Updated 11-Jul-12 0:51am
v2

I tried this and working fine..

SQL
declare @ColumnName varchar(20)
declare @Value varchar(20)

set @ColumnName='Some Column Name'
set @Value='Some value'

print @ColumnName
print @Value
select * from Student_mst Where '+ @ColumnName +' = '''+ @Value + '''

declare @query nvarchar(100)
set @query= 'select * from Student_mst Where '+ @ColumnName +' = '''+ @Value + ''''

print @query


--select * from mytablename Where name = 'RWERWRWE'





Thanks

Ashish

mark it answer if it is a solution.
 
Share this answer
 
v2
Comments
R. Ganesh Kumar IT 11-Jul-12 7:01am    
Hello Ashish I've tried it but still the same
Prasad_Kulkarni 11-Jul-12 7:04am    
Yes. A 5!
AshishChaudha 11-Jul-12 7:17am    
Thanks prasad
AshishChaudha 11-Jul-12 7:15am    
Try this query please

select * from Student_mst Where '+ @ColumnName +' = '''+ @Value + '''
R. Ganesh Kumar IT 11-Jul-12 7:30am    
I did that too. Its still the same

I tried by Entering the column name directly with value as scalar variable I got the output.
When I tried entering the value directly and the column name as scalar variable no data is retrieved
Hi Friend....

Please mentioned the size of varchar.

SQL
declare @ColumnName varchar(30)
declare @Value varchar(30)
 
Share this answer
 
Comments
Prasad_Kulkarni 11-Jul-12 7:05am    
To the point +5
Both solutions are correct for more you can refer.
Transact-SQL Variables[^] which gives you details of declaring a Transact-SQL Variable
 
Share this answer
 

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