如何检查逗号分隔的整数值" IF"条件T-SQL?

时间:2015-06-11 15:20:05

标签: sql sql-server tsql

一个简单的表包含一个带整数值的列。图如下所示。

A table named model with one column 'numbers'

我正在使用COALESCE构建'数字'用逗号。

comma delimited value

所以,现在我在IF条件中检查上面构造的值时出现问题,如下所示。它显示无法将varchar数据类型转换为整数的错误。

enter image description here

现在如何在不更改逻辑的情况下检查IF条件中的构造值?我是T-SQL的新手。谢谢你

3 个答案:

答案 0 :(得分:2)

当您连接所有数字时,您将其转换为字符串,因此它不再像整数一样。如果要检查列表中的值,请直接执行。 SQL在不同的行中具有不同的值,并以这种方式使用它们。试试这个:

DECLARE @failIds INT = 23;

IF @failIds IN (SELECT numbers FROM model)
BEGIN
    PRINT 'YES'
END
ELSE
BEGIN
    PRINT 'NO'
END

答案 1 :(得分:1)

您应该使用表变量temp,而不是以逗号分隔的字符串。表或只是原始表。例如,像这样:

declare @Ids table (id int)

insert into @Ids
select numbers
from model
where numbers in (23,234)

declare @failIds int = 23

if (exists (select 1 from @Ids where id = @failIds)) begin
  print 'Yes'
end else begin
  print 'No'
end

但你当然也可以这样做:

if (exists (select 1 from model where numbers = @failIds)) begin
  print 'Yes'
end else begin
  print 'No'
end

答案 2 :(得分:0)

我很懒于思考,最后我得到的回答如下。它非常简单。

enter image description here