Click here to Skip to main content
15,908,013 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I want to generate dynemic query according to some condition,i made it on my C# page then query work well, now my condition is i want to make this same query in Store procedure,

but my problem is how are pass string value into this query,
this is my code..




SQL
ALTER PROCEDURE [dbo].[proc_JugmentSearchCount]

    @Favour  nvarchar(MAX)='Partly',
AS
BEGIN
      SET NOCOUNT ON;
      DECLARE @DynamicSQL nvarchar(max)

      SET @DynamicSQL = 'SELECT  count(jid)  FROM tblJudgements1  where scategoryname=''Judgements'''


         Set @DynamicSQL = @DynamicSQL + ' And (favour =' +@Favour+')'

      EXECUTE sp_executesql @DynamicSQL
END



the query not take the value of "@Favour" string, and if i write query like this then it work well..

SQL
SET @DynamicSQL = 'SELECT  count(jid)  FROM tblJudgements1  where scategoryname=''Judgements'''


        Set @DynamicSQL = @DynamicSQL + ' And (favour =''partly'')'

     EXECUTE sp_executesql @DynamicSQL





but in my case the value of @Favour is came at my C# page...

so what can i do... plz help.....
Posted
Updated 6-Jan-14 6:27am
v3

All you needed to debug this was to add the line
SQL
SELECT @DynamicSQL 
at the end of your code. It would have shown you that you are missing the quotes around "Partly".


Replace line 8 with
SQL
Set @DynamicSQL = @DynamicSQL + ' And (favour =''' +@Favour+''')'
 
Share this answer
 
Comments
Arun kumar Gauttam 6-Jan-14 14:18pm    
thanks sir...
This is insane. Why would you use EXEC, which bypasses the protection you get from injection attacks, and pretend you're using stored procs ? Why not just do:

SELECT  count(jid)  FROM tblJudgements1  where scategoryname='Judgements' and (favour = @favour


Also, you'd do better to store categories and favours in tables, and then map to them via ids instead of strings.
 
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