如何在SQL Server中的两个varchar列之间进行选择

时间:2016-11-22 07:51:38

标签: sql-server sql-server-2008

我尝试在SQL Server中的值之间选择一些行,但它不起作用。

过去我在Oracle中做过类似的事情。

这是我的代码

  Select * 
  From TABLENAME 
  Where CU_CODE Between 'ELCTRN/6601' and 'ELCTRN/6699'  

请有人帮助我吗?

3 个答案:

答案 0 :(得分:1)

试试这个:

Select  * 
From TABLENAME 
WHERE   CAST(RIGHT(CU_CODE,4) AS INT) Between 6601 and 6699

答案 1 :(得分:0)

DECLARE @T TABLE (CU_CODE  NVARCHAR(50));

    INSERT INTO @T  
    VALUES('ELCTRN/6601'),
    ('ELCTRN/6602'),
    ('ELCTRN/6603'),
    ('ELCTRN/6605'),
    ('ELCTRN/668'),
    ('ELCTRN/661'),
    ('ELCTRN/662') ;

    SELECT * FROM 
    (
    SELECT CU_CODE,SUBSTRING(CU_CODE, PATINDEX('%[0-9]%', CU_CODE),       LEN(CU_CODE)) AS CODE FROM @T
    ) AS T 
    WHERE CODE BETWEEN 6601 AND 6603

答案 2 :(得分:0)

你的做法没有错......试试这个:

DECLARE @tbl TABLE (CU_CODE  NVARCHAR(50));

INSERT INTO @tbl VALUES
  (N'ELCTRN/6601')
, (N'ELCTRN/6602')
, (N'ELCTRN/6603')
, (N'ELCTRN/6604')
, (N'ELCTRN/6605')
, (N'ELCTRN/6606')
, (N'ELCTRN/6607');

SELECT * 
FROM @tbl AS tbl
WHERE tbl.CU_CODE BETWEEN N'ELCTRN/6603' AND N'ELCTRN/6605'