嗯,为什么你的专栏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 Value1
isA010
和Value2
isA029
那么它会变得更复杂一些:
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;
看看有多丑?请您考虑修复这个糟糕的设计,这样您就不必在代码库中乱扔这样的意大利面条查询了吗?