如何在动态查询中使用IN运算符

时间:2015-05-05 08:51:39

标签: c# sql-server-2008 dynamicquery

我想在动态查询中使用in运算符。目前,我需要有人指出正确的方向,如何构造撇号来分离值,以便它们不会干扰动态查询结构的撇号。这是问题的一部分,所以我需要知道的是如何放置分隔符,以便所有值都可以包含在动态查询格式中,而不是我现在的常规查询格式

WHERE ai.ImNumber != me.Company 
    AND me.ID IN ('value1','value2','value2','value3','value4','value5')' 

我的查询

SET @SQLString = 'select me.EventID , ai.AggregateInfo, '''+@DateBegin+''' AS DateBegin, '''+@EDateEnd+''' AS DateEnd 
FROM tbl_MajorEarners me 
INNER JOIN tbl_currentearners e ON e.EventID = me.EventID 
INNER JOIN tbl_AggregateInfo ai ON ai.AggregateID = cs.ItemID 
WHERE ai.ImNumber != me.CompanyNUmber 
AND me.ID IN ('value1','value2','value2','value3','value4','value5')'

1 个答案:

答案 0 :(得分:0)

我认为这就是你要找的东西

SET @SQLString = 'select me.EventID , ai.AggregateInfo, ''@DateBegin'' AS DateBegin, ''@EDateEnd'' AS DateEnd 
FROM tbl_MajorEarners me 
INNER JOIN tbl_currentearners e ON e.EventID = me.EventID 
INNER JOIN tbl_AggregateInfo ai ON ai.AggregateID = cs.ItemID 
WHERE ai.ImNumber != me.CompanyNUmber 
AND me.ID IN (''value1'',''value2'',''value2'',''value3'',''value4'',''value5'')'

@SqlString设置为

select me.EventID , ai.AggregateInfo, '@DateBegin' AS DateBegin, '@EDateEnd' AS DateEnd 
FROM tbl_MajorEarners me 
INNER JOIN tbl_currentearners e ON e.EventID = me.EventID 
INNER JOIN tbl_AggregateInfo ai ON ai.AggregateID = cs.ItemID 
WHERE ai.ImNumber != me.CompanyNUmber 
AND me.ID IN ('value1','value2','value2','value3','value4','value5')