传递给LEFT或SUBSTRING函数的长度参数无效

时间:2014-02-05 08:50:08

标签: sql sql-server-2008 substring

以下是我的查询,当我喜欢TRAILER_MAKE_MODEL '测试〜测试,测试~testq,'以逗号结尾但无法处理'测试〜测试时,它工作正常~testq'与其他变量TRAILER_IDV相同。我尽我所能,但无法解决任何帮助将不胜感激 我的目标是获取xml的逗号分隔值。

DECLARE @TRAILER_MAKE_MODEL VARCHAR(MAX)
DECLARE @TRAILER_IDV VARCHAR(MAX)
DECLARE @USER_TYPE VARCHAR(MAX)

DECLARE @START_INDEX_1 INT
DECLARE @START_INDEX_4 INT

DECLARE @END_INDEX_1 INT
DECLARE @END_INDEX_4 INT

DECLARE @VALUE VARCHAR(50)

DECLARE @QUERY VARCHAR(MAX)
set @TRAILER_MAKE_MODEL='testing ~ testing, test ~ testq,' 
set @TRAILER_IDV='3500, 3400,'
set @USER_TYPE='MOBILE'

 set @QUERY = ''

set @START_INDEX_1 = 1
set @START_INDEX_4 = 1
set @END_INDEX_1 = 0
if ISNULL(@TRAILER_MAKE_MODEL,'') <> ''
begin
 WHILE @START_INDEX_1 > 0 and @START_INDEX_1 < len(@TRAILER_MAKE_MODEL)
BEGIN
SET @END_INDEX_1 = CHARINDEX(',',@TRAILER_MAKE_MODEL,@START_INDEX_1)
if @END_INDEX_1 = 0 and @START_INDEX_1 = 1
Begin
    SET @END_INDEX_1 = len(@TRAILER_MAKE_MODEL)
END 
if @USER_TYPE <> 'MOBILE'
Begin 
    SET @END_INDEX_1 = @END_INDEX_1 +1
End
SET @VALUE = SUBSTRING(@TRAILER_MAKE_MODEL,@START_INDEX_1,@END_INDEX_1 - @START_INDEX_1)
SET @QUERY = @QUERY + 'UNION ALL SELECT ''' + @VALUE + ''' TRAILER_MAKE_MODEL'


SET @END_INDEX_4 = CHARINDEX(',',@TRAILER_IDV,@START_INDEX_4)
if @END_INDEX_4 = 0 and @START_INDEX_4 = 1
Begin
    SET @END_INDEX_4 = len(@TRAILER_IDV)
END
if @USER_TYPE <> 'MOBILE'
Begin 
    SET @END_INDEX_4 = @END_INDEX_4 +1
End
SET @VALUE = SUBSTRING(@TRAILER_IDV,@START_INDEX_4,@END_INDEX_4 - @START_INDEX_4)
SET @QUERY = @QUERY + ',' + @VALUE + 'TRAILER_IDV '
print @QUERY
SET @START_INDEX_1 = @END_INDEX_1 + 1   
SET @START_INDEX_4 = @END_INDEX_4 + 1

END
select @QUERY=substring(@QUERY, 10, LEN(@QUERY) - 9)
EXEC (@QUERY) 
END  

1 个答案:

答案 0 :(得分:2)

你已经有了很多代码,所以在每个字符串的末尾分配一个逗号的两个额外行可能不会减慢你的速度或使代码不易维护。

SET @TRAILER_MAKE_MODEL += ',';
SET @TRAILER_IDV += ',';

我真的不明白你的代码是做什么的,但是为了得到你得到的结果你可以使用split string function来返回这样的项目的索引。

select T1.Item as TRAILER_MAKE_MODEL,
       T2.Item as TRAILER_IDV
from dbo.SplitString(@TRAILER_MAKE_MODEL, ',') as T1
  inner join dbo.SplitString(@TRAILER_IDV, ',') as T2
    on T1.ItemNumber = T2.ItemNumber