简体   繁体   中英

Get N th row value in sql server

      DECLARE @ActionNumber varchar(20)='EHPL-DES-SQ-1021'
         set @ActionNumber=(select top 1 * from dbo.ANOSplit(@ActionNumber,'-')
         order by ROW_NUMBER() OVER (ORDER BY  items))
         select @ActionNumber

from above query i need to return the 2ND and 3RD index from initial @ActionNumber ' EHPL-DES-SQ-1021 ' after Split() .

format of the ActionNumber is exactly as above but DES , SQ and 1021 can change.

so i can not use ORDER BY items ASC or ORDER BY items DESC because it will order alphabetically.

above query returns 'EHPL'.how can i get DES and SQ.

You can do it with the ANOSplit function, but I would insert the result into a temp table or table variable.
As you said yourself, you can't just ORDER BY the values returned by the ANOSplit function because it will order alphabetically.
--> So you can use a temp table with an IDENTITY column, and use this for sorting:

DECLARE @ActionNumber varchar(20)='EHPL-DES-SQ-1021'

declare @tmp table
(
    id int identity(1,1),
    item varchar(20)
)

insert into @tmp (item)
select * from dbo.ANOSplit(@ActionNumber,'-')

select * from @tmp where id in (2,3)

The items will be inserted into the table in the exact order returned by the function, so after inserting you know that the lines with id 2 and 3 are the ones you want.

Try to use Substring with CharIndex >>>

DECLARE @ActionNumber varchar(20)='EHPL-DES-SQ-1021'
select SUBSTRING (@ActionNumber,CHARINDEX ('-',@ActionNumber,0) + 1, 3)

This isn't tested, but I think it will work:

DECLARE @ActionNumber varchar(20)='EHPL-DES-SQ-1021'
WITH nCTE AS
(
    SELECT
        ROW_NUMBER() OVER (ORDER BY  items) AS RNum

    FROM dbo.ANOSplit(@ActionNumber,'-')
)
SELECT * FROM nCTE WHERE RNum = 2   --put n here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM