简体   繁体   中英

SQL SELECT substring using variable

I have the following query:

SELECT 
    SUBSTRING('Message-ID=<6aasd2k4081-f6asdasc134-43asd45c-b2asd32429-a32ad410de78@comunic.local.test.global>, Authentication-Results',
    (SELECT CHARINDEX(' Message-ID=<','Message-ID=<6aasd2k4081-f6asdasc134-43asd45c-b2asd32429-a32ad410de78@comunic.local.test.global>, Authentication-Results') +1),
CHARINDEX('>, Authentication-Results', 'Message-ID=<6aasd2k4081-f6asdasc134-43asd45c-b2asd32429-a32ad410de78@comunic.local.test.global>, Authentication-Results') 
-CHARINDEX(' Message-ID=<','Message-ID=<6aasd2k4081-f6asdasc134-43asd45c-b2asd32429-a32ad410de78@comunic.local.test.global>, Authentication-Results') -1)

This works just fine when I run it (no errors).

I am trying to do the same thing but now using a variable which has the value returned from a select statement:

DECLARE @itemProp nvarchar(max);
set @itemProp=  (SELECT ItemProperties FROM [table1] where colID=1)

SELECT SUBSTRING(@itemProp,
(SELECT CHARINDEX(' Message-ID=<',@itemProp) +1),
CHARINDEX('>, Authentication-Results', @itemProp) 
-CHARINDEX(' Message-ID=<',@itemProp) -1)

When I run this query, I get the following error:

Invalid length parameter passed to the SUBSTRING function.

The value of the @itemProp assigned by the select statement is same as in the first example:

'Message-ID=<6aasd2k4081-f6asdasc134-43asd45c-b2asd32429-a32ad410de78@comunic.local.test.global>, Authentication-Results'. 

Also, I am using SQL Server 2005.

Any help is appreciated - thanks

Your query is looking for ' Message-ID=<' , with a space at the beginning. That doesn't seem to be in the string. Try this instead:

SELECT SUBSTRING(@itemProp,
                 CHARINDEX('Message-ID=<', @itemProp) +1,
----------------------------^
                 CHARINDEX('>, Authentication-Results', @itemProp) - CHARINDEX('Message-ID=<',@itemProp) -1
--------------------------------------------------------------------------------^
                )

Note there are no spaces at the indicated positions.

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