sql - 使用 Left 和 char 索引返回无效参数
问题描述
当我结合 left 和 charindex 我得到一个无效的参数 left
我的行返回类似产品名称、产品名称、其他一些文本我只想获取产品名称
所以通过使用 charindex 我可以得到总字符直到第一个逗号
使用 charindex(',',[列名])
例子
[productinformation] 为列名
这是返回的完整列
select [productinformation] from testTable
蓝色小部件,1313138,一盒 300 件
select charindex(',',[productinformation]) from testTable
将返回 12
使用 testTable 中的 select left([productinformation]),charindex(',',[productinformation]))
返回
blue widget,
使用 select charindex(','[productinformation]) -1 from testTable 返回 11
所以我假设从 charindex 中减去一个只会给我产品名称。
SELECT left([productinformation],charindex(','[productinformation])-1) FROM testTable
返回
Invalid length parameter passed to the LEFT or SUBSTRING function
解决方案
该LEFT()
函数只接收正整数
integer_expression 是一个正整数,指定将返回 character_expression 的多少个字符。如果 integer_expression 为负数,则返回错误。如果 integer_expression 是 bigint 类型并且包含一个大值,则 character_expression 必须是大数据类型,例如 varchar(max)。
所以,如果你CHARINDEDX()
没有找到 char 它会返回0
,然后你添加-1
,那么0-1
就是-1
。
那会抛出一个错误
传递给 LEFT 或 SUBSTRING 函数的长度参数无效
您需要检查返回值是否为正
SELECT LEFT([productinformation],
CASE WHEN CHARINDEX(',',[productinformation]) > 1
THEN CHARINDEX(',',[productinformation]) - 1
WHEN CHARINDEX(',',[productinformation]) = 1
THEN 1
ELSE LEN([productinformation]) --if you want to return it all otherwise 0
-- if you set it to 0 it will return ''
END
)
FROM testTable