我正在尝试构建一个可以将组合的产品描述,颜色和大小分成各个值的查询。我有一张桌子,里面有产品描述,颜色和尺寸。某些产品说明包含每个用特定字符串分隔的颜色和大小。一些颜色和大小包含在它们自己的列中。很多时候,描述和颜色/大小列都包含颜色/大小值。结合颜色和大小的常见产品说明如下所示: ProductDescription ..- ..颜色 - .--颜色由" ..- .."分隔的尺寸。和大小由" - .--"分隔。有时颜色和/或大小不存在,并且查询没有分隔符引用,但我仍然希望它分割描述/颜色或描述/大小,或者只返回颜色/大小的描述和空白值既不存在......
描述和尺寸分割得很好,但我遇到颜色问题。我收到以下错误:
Invalid length parameter passed to the LEFT or SUBSTRING function.
非常感谢任何帮助!
这是我到目前为止所做的工作:
Select
Ps.ID
,Case
When Ps.ColorStart <= 5 And Ps.SizeStart <= 5 Then Ps.Description
When Ps.ColorStart <= 5 And Ps.SizeStart > 5 Then Left(Ps.Description, Ps.SizeStart - 6)
When Ps.ColorStart > 5 Then Left(Ps.Description, Ps.ColorStart - 6)
Else Ps.Description
End As DescriptionWithoutColorAndSize
,Case
When Ps.PColor Is Not Null And Ps.PColor <> '' Then Ps.PColor
When Ps.ColorStart <= 5 Or Ps.Description Is Null Or Ps.Description = '' Then ''
When Ps.SizeStart <= 5 And Ps.ColorStart > 5 Then SUBSTRING(Ps.Description, Ps.ColorStart, 299)
When Ps.SizeStart > 5 And Ps.ColorStart > 5 Then SUBSTRING(Ps.Description, Ps.ColorStart, Ps.ColorEndIfSizeExists - Ps.ColorStart + 1)
--The prior line is what fails
Else ''
End As Color
,Case
When Ps.PSize Is Not Null And Ps.PSize <> '' Then Ps.PSize
When Ps.SizeStart <= 5 Then ''
Else SUBSTRING(Ps.Description, Ps.SizeStart, 299)
End As Size
From
(
Select
P.ID
,P.Description
,P.Color As PColor
,P.Size As PSize
,CHARINDEX('..-..',P.Description,0) + 5 As ColorStart
,CHARINDEX('--.--',P.Description,0) -1 As ColorEndIfSizeExists
,Len(P.Description) As ColorEndIfSizeDoesNotExist
,CHARINDEX('--.--',P.Description,0) + 5 As SizeStart
From
MYProductsTable P
) Ps
答案 0 :(得分:0)
所有问题都与以下案例陈述有关:
,Case
When Ps.PColor Is Not Null And Ps.PColor <> '' Or Ps.ColorEndIfSizeExists - Ps.ColorStart + 1 < 0 Then Ps.PColor
When Ps.ColorStart <=5 Or Ps.Description Is Null Or Ps.Description = '' Then ''
When Ps.SizeStart <=5 And Ps.ColorStart > 5 Then SUBSTRING(Ps.Description, Ps.ColorStart, 299)
When Ps.SizeStart > 5 And Ps.ColorStart > 5 Then SUBSTRING(Ps.Description, Ps.ColorStart, Ps.ColorEndIfSizeExists - Ps.ColorStart + 1)
Else ''
End As Color
我将“&lt; = 5”的所有实例更改为“&lt; 6”,并在下面添加了一个新的时间:
,Case
When Ps.ColorEndIfSizeExists - Ps.ColorStart + 1 < 0 Then SUBSTRING(Ps.Description, Ps.ColorStart, 299)
When Ps.PColor Is Not Null And Ps.PColor <> '' Then Ps.PColor
When Ps.ColorStart <6 Or Ps.Description Is Null Or Ps.Description = '' Then ''
When Ps.SizeStart <6 And Ps.ColorStart > 5 Then SUBSTRING(Ps.Description, Ps.ColorStart, 299)
When Ps.SizeStart > 5 And Ps.ColorStart > 5 Then SUBSTRING(Ps.Description, Ps.ColorStart, Ps.ColorEndIfSizeExists - Ps.ColorStart + 1)
Else ''
End As Color
这解决了这个问题。我不知道为什么......如果有人这样做,请随时解释! 感谢您的所有投入。