简体   繁体   中英

Use of CHARINDEX and SUBSTRING to get a substring between brackets from a string

The expression I'd need is that but it fails ('Command has been aborted') because of the '-1'. But without this '-1' it gives me one character too many.

select SUBSTRING(M_COMMENT,CHARINDEX('[',M_COMMENT)+1,CHARINDEX(']',M_COMMENT) - CHARINDEX('[',M_COMMENT)-1) from TRN_EODA_DBF

But it works fine with the '+1' which I don't understand.

select SUBSTRING(M_COMMENT,CHARINDEX('[',M_COMMENT)+1,CHARINDEX(']',M_COMMENT) - CHARINDEX('[',M_COMMENT)+1) from TRN_EODA_DBF

Thanks for your help.

If your version of Sybase supports CROSS APPLY this works approach quite well:

SELECT
      CASE
            WHEN pos1 > 1 THEN SUBSTRING(M_COMMENT, pos1 + 1, CHARINDEX(']', M_COMMENT) - pos1 - 1)
            END
FROM TRN_EODA_DBF
      CROSS APPLY (
                  SELECT
                        CHARINDEX('[', M_COMMENT)
            ) ca (pos1)

+EDIT! Oh dear, sory. I typed CROSS JOIN, but I meant CROSS APPLY - very sorry

|                 INPUT |        OUTPUT | POS1 |
|-----------------------|---------------|------|
| admin@[sqlfiddle.com] | sqlfiddle.com |    7 |
|            @sqlfiddle |        (null) |    0 |
|         @jake[feasel] |        feasel |    6 |

example

SELECT
       M_COMMENT as input
     , CASE
            WHEN pos1 > 1 THEN SUBSTRING(M_COMMENT, pos1 + 1, CHARINDEX(']', M_COMMENT) - pos1 - 1)
            END
       AS output
     , pos1
FROM TRN_EODA_DBF
      CROSS APPLY (
                  SELECT
                        CHARINDEX('[', M_COMMENT)
            ) ca (pos1)

Without cross apply you can do the same thing but you repeat use of charindex instead:

SELECT
       M_COMMENT as input
     , CASE
            WHEN CHARINDEX('[', M_COMMENT) > 1 THEN SUBSTRING(M_COMMENT, CHARINDEX('[', M_COMMENT) + 1, CHARINDEX(']', M_COMMENT) - CHARINDEX('[', M_COMMENT) - 1)
            END
       AS output
FROM TRN_EODA_DBF

Demo

Thanks, I'll try this one. By the way I found this very detailed post explaining why I have this error message: http://www.sql-server-helper.com/error-messages/msg-536.aspx

It says:"This error is caused by passing a negative value to the length parameter of the SUBSTRING, LEFT and RIGHT string functions. This usually occurs in conjunction with the CHARINDEX function wherein the character being searched for in a string is not found and 1 is subtracted from the result of the CHARINDEX function."

This is exactly what happens 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