SQL搜索多个字段,返回一个

时间:2009-12-10 16:13:40

标签: sql sql-server-2005 tsql

我有一个查询需要将值与多列进行比较,并且只返回一个结果。当我尝试将字符串参数转换为整数时,我不断收到转换错误,但是我无法找到绕过它的好方法。

SELECT DISTINCT
  CASE
    WHEN table_one.integer_col = CAST('argument%' AS int)
        THEN table_one.integer_col
    WHEN table_one.varchar_col LIKE 'argument%'
        THEN table_one.varchar_col
    WHEN table_two.varchar_col LIKE 'argument%'
  END
  FROM table_one
  INNER JOIN table_two
  ON table_one.pk=table_two.fk
  WHERE
    table_one.integer_col = CAST('argument%' AS int)
    table_one.varchar_col LIKE 'argument%' OR
    table_two.varchar_col LIKE 'argument%'

当'argument%'可以成功转换为整数时,这种方法有效,但是当它不能时,查询会发生炸弹。

2 个答案:

答案 0 :(得分:3)

如何将整数转换或转换为varchar数据类型? 不是将varchar搜索参数转换为int以匹配int列,而是将int列转换为varchar。

这是一个简单的例子。

DECLARE @Table  TABLE
(
someInt     int
)

INSERT INTO @Table (SomeInt)
    SELECT  1234567 UNION ALL
    SELECT  98765 UNION ALL
    SELECT  24680 UNION ALL
    SELECT  13579 UNION ALL
    SELECT  963852 UNION ALL
    SELECT  147258 




SELECT * 
    FROM @Table 
    WHERE CAST(SomeInt AS varchar(10)) LIKE '1%'

---- Results
1234567
13579
147258

答案 1 :(得分:2)

SELECT DISTINCT
  CASE
    WHEN CAST(table_one.integer_col AS VARCHAR(MAX)) LIKE 'argument%'
        THEN table_one.integer_col
    WHEN table_one.varchar_col LIKE 'argument%'
        THEN table_one.varchar_col
    WHEN table_two.varchar_col LIKE 'argument%'
  END
  FROM table_one
  INNER JOIN table_two
  ON table_one.pk=table_two.fk
  WHERE
    CAST(table_one.integer_col AS VARCHAR(MAX)) LIKE 'argument%' OR
    table_one.varchar_col LIKE 'argument%' OR
    table_two.varchar_col LIKE 'argument%'