Click here to Skip to main content
15,895,256 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
i am trying to generate a dynamic where clause in my store proc.

=== @population nvarchar(max)

declare    @chvSelect varchar(max),
             @chvFrom varchar(max),
             @chvWhere varchar(max),
             @chvOrderby varchar(max),
             @chvSQL varchar(max)
BEGIN
 

--if @Population is not null

set @chvSelect='SELECT Localities.Name,FormFields.FieldName, FormInstanceData.Value'  
set @chvFrom=' FROM   FormInstances INNER JOIN
                      FormInstanceData ON FormInstances.Id = FormInstanceData.FormInstanceId INNER JOIN
                      Communities INNER JOIN
                      Localities ON Communities.Id = Localities.Id INNER JOIN
                      WCData ON Localities.Id = WCData.LocalityId ON FormInstances.Id = WCData.FormInstanceId INNER JOIN
                      FormFields ON FormInstanceData.FieldId = FormFields.Id '
set @chvWhere=' WHERE FormFields.FieldName =' + @Population 
--if @Population is not null

--set @chvWhere=@chvWhere + 'FormFields.FieldName =' + CONVERT(varchar,@Population )
set @chvSQL = @chvSelect+ @chvFrom + @chvWhere 
select @chvSQL Query
  --if @debug = 0
        exec (@chvSQL)
  --   else
   --    select @chvSQL

END

when i exec this i get invalid Column name ('whatever value i supplied to the @population' actually the formfields .fieldname is the column and the values i supply are supposes be values contained by that column.)
Posted

#Jet wrote:
FormInstances INNER JOIN FormInstanceData ON FormInstances.Id = FormInstanceData.FormInstanceId INNER JOIN Communities INNER JOIN Localities

Looks like error is here... Query is not properly formed. You have multiple INNER JOINS back to back without the join condition.

Furhter, how do you know the the invalid column error is in WHERE clause. For debug purpose (to catch the error line) Would suggest you to use print each line set by you for forming query. Use the print outputs, concatenate it and check where exactly it shows you wrong (if you can get through naked eyes well enough!)
 
Share this answer
 
Try this...check if more comma(s) required...The variable value should be passed within single quote to dynamic query in such a way that it should be again become a string

set @chvWhere=' WHERE FormFields.FieldName =''' + @Population + ''
 
Share this answer
 
v2
As referred above by "S Mewara"

Looks like problem with your Inner Join.
 
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