简体   繁体   English

SQL SELECT子字符串使用变量

[英]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: 我正在尝试做同样的事情,但现在使用的变量具有从select语句返回的值:

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. 无效的长度参数传递给SUBSTRING函数。

The value of the @itemProp assigned by the select statement is same as in the first example: select语句分配的@itemProp的值与第一个示例中的相同:

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

Also, I am using SQL Server 2005. 另外,我正在使用SQL Server 2005。

Any help is appreciated - thanks 任何帮助表示赞赏-谢谢

Your query is looking for ' Message-ID=<' , with a space at the beginning. 您的查询正在寻找' Message-ID=<' ,并以空格开头。 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. 请注意,在指示的位置没有空格。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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