光标以获得所需的结果

时间:2017-02-24 13:03:48

标签: sql-server sql-server-2008

我有这样的表:

x------x---------x----------------------x-------x
|  Id  |   ACCTNO  |   name2             |  QTY  |
x------x---------x----------------------x-------x
|   1  |   1     | here is 2014-01-13   |  10   |
|   1  |   2     | there are 2014-01-12  |  20   |
|   2  |   3     | 2014-01-08           |  40    |
|   2  |   4     | 2014-01-06           |  30    |
x------x---------x----------------------x-------x 

我正在尝试记录英文字母和日期的记录。

我试图这样做:

DECLARE @ACCTNO as INT;
DECLARE @name2 as varchar(max);
declare @st varchar(max)

DECLARE @BusinessCursor as CURSOR;


SET @BusinessCursor = CURSOR FOR
SELECT ACCTNO, Name2
FROM DPBENCHA2;

  OPEN @BusinessCursor;
   FETCH NEXT FROM @BusinessCursor INTO @ACCTNO, @name2;
    --PRINT  @Name2;

     WHILE @@FETCH_STATUS = 0
     BEGIN

     set @st = @Name2;
     select SUBSTRING(@st, patindex('%[0-9][0-9]/[0-9][0-9]/[0-9][0-9]%', @st), 50)
      PRINT @st;
     FETCH NEXT FROM @BusinessCursor INTO @ACCTNO,@st;
    END

   CLOSE @BusinessCursor;
   DEALLOCATE @BusinessCursor;

此处不是获取包含英文字母和日期的记录。我收到了所有记录。怎么解决这个?如何仅为帐号1和2获取记录?有没有其他方法可以做到。

3 个答案:

答案 0 :(得分:5)

  

我正在尝试记录英文字母和日期的记录。

您似乎想要一个简单的查询:

SELECT ACCTNO, Name2
FROM DPBENCHA2
WHERE name2 LIKE '%[a-zA-Z]%';

这比光标简单得多。通常,您希望避免使用SQL中的游标。

编辑:

如果您想从Name2提取日期:

SELECT ACCTNO, Name2,
       SUBSTRING(name2,
                 PATINDEX('%[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]%'),
                 10) as thedate
FROM DPBENCHA2
WHERE name2 LIKE '%[a-zA-Z]%';

答案 1 :(得分:0)

使用如下

SUBSTRING(@st, patindex('%[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]%', @st), 50)

答案 2 :(得分:0)

您可以使用简单的选择,假设您的日期格式为yyyy-dd-mmyyyy-mm-dd

select * from DPBENCHA2 where  (name2 like '%[a-z]%')

 and name2 like '% [0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]%'

请注意'%<space>[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]%'

中的空格

这将确保'some alphabet 22323-12-34'不会包含在您的选择

相关问题