Click here to Skip to main content
15,888,461 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
here is my stored procedure .. i give column name dynamically
SQL
@datafield varchar(30) --> this column name which i enter
AS
BEGIN
SELECT cust_id  FROM custm_master where @datafield = 1
END

exec cust_search 'cust_id' --> column name


i got an error :
SQL
Conversion failed when converting the nvarchar value '[cust_id]' to data type int.
Posted

You can't do it like that: The parameter substitution is done at a different stage of the SQL processing, so that won't work. What you have to do is create a string and execute that:
SQL
DECLARE @CMD VARCHAR(MAX)
SET @CMD = 'SELECT cust_id FROM custm_master WHERE ' + @datafield + '=1'
EXEC(@CMD)
 
Share this answer
 
Comments
priyanshbhaliya 6-Oct-13 11:29am    
thnks and can u explain why my query give error to convert column name to int
OriginalGriff 6-Oct-13 11:39am    
It has to do with the order in which things happen.
The query is processed into an internal form and is systemax checked at the point.
When this parser looks at the query is assumes that the condition is trying to compare a parameter value with a number - so it generates internal code to convert your parameter value to an integer when it gets to the execution stage.
When that code gets executed, it finds it's not convertible and throws an error.
priyanshbhaliya 6-Oct-13 11:52am    
thnks
priyanshbhaliya 6-Oct-13 12:08pm    
ur query give an error : must declare scalar variable '@datafield'
OriginalGriff 6-Oct-13 12:12pm    
It's your parameter name - so you need that code in your SP...
try this way-

SQL
@datafield varchar(30) --> this column name which i enter
AS
BEGIN
declare @SQL varchar(8000)
declare @val varchar(100)='1'
set @SQL='SELECT cust_id  FROM custm_master where  '+ @datafield +' = ''' + @val+''''
exec (@sql)
END
 
Share this answer
 
Comments
priyanshbhaliya 6-Oct-13 11:28am    
thnks and can u explain why my query give error to convert column name to int
priyanshbhaliya 6-Oct-13 11:59am    
why u give @val field 3 quote in both side ???
Madhu Nair 7-Oct-13 1:43am    
you can remove it if not required.... i have used it in case you want to pass varchar data
priyanshbhaliya 8-Oct-13 3:43am    
ok thnks

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