Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>If I understand your question correctly, the code below should work. Note that I've created a function to help with the string concatenation. I'm not sure if you wanted to AND or OR your conditions. I've used AND in my sample. You can easily adjust it for OR if that's appropriate.</p> <pre><code>/* Set up sample data */ create table FilterData ( CategoryID char(4), ColumnID char(3), AnswerCode char(2) ) insert into FilterData (CategoryID, ColumnID, AnswerCode) values ('0349','Q15','02') insert into FilterData (CategoryID, ColumnID, AnswerCode) values ('0349','Q15','03') insert into FilterData (CategoryID, ColumnID, AnswerCode) values ('0349','Q16','04') go /* Helper function to concatenate all AnswerCodes for a given ColumnID */ create function dbo.fnStringAnswerCodes(@ColumnID char(3)) returns varchar(1000) as begin declare @CodeString varchar(1000) set @CodeString = @ColumnID + ' in (' select @CodeString = @CodeString + '''' + AnswerCode + ''',' from FilterData where ColumnID = @ColumnID /* Remove trailing comma and add closing parens */ select @CodeString = left(@CodeString, len(@CodeString)-1) + ')' return @CodeString end go declare @CategoryID char(4) declare @SQLString varchar(1000) declare @WhereClause varchar(1000) set @CategoryID = '0349' set @SQLString = 'select * from TransactionData ' set @WhereClause = 'where CategoryID=''' + @CategoryID + ''' and ' select @WhereClause = @WhereClause + dbo.fnStringAnswerCodes(ColumnID) + ' and ' from FilterData where CategoryID = @CategoryID group by ColumnID /* Remove Trailing 'AND' */ set @WhereClause = LEFT(@WhereClause, len(@WhereClause)-3) set @SQLString = @SQLString + @WhereClause select @SQLString /* Last step would be to dynamically execute the string we built */ /* exec sp_ExecuteSQL @SQLString */ /* Clean Up */ drop function dbo.fnStringAnswerCodes drop table FilterData </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload