Click here to Skip to main content
15,879,037 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
Hello to All

I have a store procedure like
SQL
declare @CName as varchar(50)='SalInvNo';
declare @qry as nvarchar(500)
declare @count as int
set @qry='select @count = count(*) from table;
set @qry+=' where '+@CName+' <> 0';
exec sp_executesql @qry, N'@count int OUTPUT', @count OUTPUT



but it is giving error:
Msg 245, Level 16, State 1, Line 1
Conversion failed when converting the varchar value 'SalINV1' to data type int.


[edit]Subject, tidied code blocks - OriginalGriff[/edit]
Posted
Updated 18-Mar-11 22:23pm
v2

Why would you build and execute a string for this?
Executing strings is usually not best practice and there are some dangers to it as well.
http://www.sommarskog.se/dynamic_sql.html[^]
In your case I would get rid of the entire @qry stuff and simply 'hardcode' the column name into the query.
 
Share this answer
 
Comments
Dalek Dave 19-Mar-11 7:17am    
Good Call.
Justin Marshall Canada 23-May-17 17:22pm    
hardcoding a parameter into DSQL is not safe you should use quotename built-in function to wrap your column name for example an unwanted guest could use a column name like

1=1; drop table x; select 1 where 1

this would result in the following query being run:
select @count = count(*) from table where 1=1; drop table x; select 1 where 1 <> 0

as you can see this would count every record in the db, drop table x and then return null for the 3rd part.

Also you have an extra ; after the first set @qry
Sander Rossel 23-May-17 17:25pm    
Hi, not only are you replying to the wrong message, you're replying to a message from 2011 (6 years old!) that has long been resolved... Appreciate the help, but please look more closely what you're replying to :-)
try this

set @qry+=' where '+@CName+' <> '''+@Temp+'''';
 
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