0

我有一个名为 Test 的表

Test
Name   Value1(varchar)   Value2(varchar)
A          1                  9
B          10                 19
C          20                 39
D          40                 45
...        ...                ...

现在,当我发送“8”或“21”等值时,如何从测试表中获取名称

4

1 回答 1

4

嗯,为什么你的专栏VARCHAR

DECLARE @n INT = 8;

SELECT Name FROM dbo.Test
  WHERE @n BETWEEN CONVERT(INT, Value1) AND CONVERT(INT, Value2);

如果您在这些列中有其他垃圾,您可能必须执行以下操作以防止 SQL Server 智取您并尝试转换'ascfdgt'为整数:

DECLARE @n INT = 8;

SELECT Name FROM dbo.Test
  WHERE ISNUMERIC(Value1) = 1
    AND ISNUMERIC(Value2) = 1
    AND @n BETWEEN CASE WHEN ISNUMERIC(Value1) = 1 THEN CONVERT(INT, Value1) END
               AND CASE WHEN ISNUMERIC(Value2) = 1 THEN CONVERT(INT, Value2) END;

现在请修复此列的数据类型,或者将这些数字存储在不同的列中。

如果您传入A12并需要查找行 where Value1isA010Value2isA029那么它会变得更复杂一些:

DECLARE @n VARCHAR(12) = 'A12';

SELECT Name FROM dbo.Test
  WHERE ISNUMERIC(SUBSTRING(Value1, 2, 255)) = 1
    AND ISNUMERIC(SUBSTRING(Value2, 2, 255)) = 1
    AND CONVERT(INT, SUBSTRING(@n, 2, 255)) 
      BETWEEN CASE WHEN ISNUMERIC(SUBSTRING(Value1, 2, 255)) = 1
        THEN CONVERT(INT, SUBSTRING(Value1, 2, 255)) END
          AND CASE WHEN ISNUMERIC(SUBSTRING(Value2, 2, 255)) = 1
        THEN CONVERT(INT, SUBSTRING(Value2, 2, 255)) END;

看看有多丑?请您考虑修复这个糟糕的设计,这样您就不必在代码库中乱扔这样的意大利面条查询了吗?

于 2013-03-14T01:48:27.953 回答