如果这不是解决这个问题的正确方法,请告诉我。
我想在变量中的AND条件后声明代码。代码是:
SELECT * FROM MyTable
WHERE Key = '12345'
AND (Condition1 or Condition2 or Condition3)我希望实现这样的目标:
DECLARE @Condition
SET @Condition = 'Condition1 or Condition2 or Condition3'
SELECT * FROM MyTable
WHERE Key = '12345'
AND @ConditionAND运算符需要一个布尔表达式,所以这不起作用。请告诉我怎样才能做到这一点。
这个想法是,我可以将@Condition存储在一个变量表(varName, varValue)中,当我想在代码中使用它时(有点像一个全局变量),就可以从那里获取它。如果我遵循这种方法,也请让我知道代码的性能是否会受到影响。
发布于 2016-08-11 09:36:23
您需要使用动态sql:
declare @sql nvarchar(max);
set @sql = 'select * from mytable where [key] = @key and @condition';
set @sql = replace(@sql, '@condition', @condition);
exec sp_executesql @sql, N'@key varchar(255)', @key = '12345';当您将@condition放在where子句中时,它将被视为字符串。就这样。没有语义分析。
发布于 2016-08-11 11:59:00
我想知道你能不能根据你的条件创建一个表变量...由于您不是非常明确这些条件是什么,所以很难判断这样的事情是否有效,但这是我有时使用的一种方法:
declare @conditions table (condition nvarchar(255), value bit);
insert into @table (condition, value)
select condition, value
from (
values ('Less than x', 1), ('Greater than y', 0))
) x (condition, value) 然后在你的where子句中使用它。
select *
from Table
where not exists (select 1 from @conditions where value = 1)或者你也可以加入其中。如果你在比较int,你可以交叉连接并说where @conditions.condition < yourTable.value。
https://stackoverflow.com/questions/38885906
复制相似问题