如何用STUFF函数在SQL Server文件名后缀前追加字符串?
在SQL Server文件名后缀前追加内容的正确实现方法
你的问题出在STUFF函数的起始位置计算上:STUFF的起始参数必须是正整数,用负数会直接返回NULL。要在4字符后缀(含点,如.txt)前插入内容,需要先计算出插入点的正确位置——也就是文件名长度减去3(因为SQL Server字符串索引从1开始计数,倒数第4位的索引是LEN(fname) - 3)。
修改后的查询语句
select fname, code, -- 处理code为NULL的情况,避免插入多余的下划线 case when code is not null then stuff(fname, len(fname) - 3, 0, concat('_', code)) else fname end as d from ( select right(a.[Path], charindex('\',reverse(a.[Path]))-1) as FName, b.Code from table_A as a left join table_B as b on a.ID_A = b.ID_B ) as a
关键说明
- 起始位置计算:
LEN(fname) - 3能准确定位到后缀前的位置。比如文件名report.csv(长度8),8-3=5,STUFF会在第5位(t和.之间)插入_code,最终得到report_code.csv。 - NULL处理:因为是左连接,
code可能为NULL,用CASE判断可以避免生成类似report_.csv的异常文件名。
如果需要兼容文件名长度不足4的极端情况(虽然你说明后缀都是4字符),可以再加一层判断确保索引不越界:
select fname, code, case when code is not null and len(fname) >=4 then stuff(fname, len(fname) - 3, 0, concat('_', code)) else fname end as d from ( select right(a.[Path], charindex('\',reverse(a.[Path]))-1) as FName, b.Code from table_A as a left join table_B as b on a.ID_A = b.ID_B ) as a
内容的提问来源于stack exchange,提问作者user1663003
相关产品推荐
相关产品推荐

