如何在字符串sql中做减号

时间:2017-05-26 04:25:41

标签: sql

我在桌子上的专栏就像FurnaceRunno(GM15-737)。所以,我想在FurnaceRunno做减1。

输出应该是这样的:(减一个值,每个炉子都没有固定)

FurnaceRunno  :GM15-737      
output        :GM15-736  

3 个答案:

答案 0 :(得分:1)

试试这个

declare @mytext varchar(10) = 'GM15-736'
declare @prefix varchar(2) = left(@mytext,2)

select @prefix + cast( replace(replace(@mytext,'-','0'),@prefix,'') + 1 as varchar(10))

答案 1 :(得分:1)

select SUBSTRING(FurnaceRunno, 0, charindex('-', FurnaceRunno, 1)) + '-' 
+ CONVERT(varchar(50), CONVERT(INT, SUBSTRING(FurnaceRunno, charindex('-', FurnaceRunno, 1) + 1, len(FurnaceRunno))) - 1)
FROM mytable

答案 2 :(得分:1)

尝试这些查询 -

-- Query 1:
DECLARE @Result INT
SET @Result = CAST(RIGHT('GM15-737', 3) AS INT) - 1
SELECT REPLACE('GM15-737', SUBSTRING('GM15-737', 6, 3), CAST(@Result AS 
VARCHAR)) 

-- Query 2:
DECLARE @Result1 INT, @OutputString VARCHAR(255)

SET @Result1 = CAST(SUBSTRING(REPLACE('GM15-737', '-', ''), 3, 5) AS INT) - 1
SET @OutputString = CONCAT('GM', CAST(@Result1 AS VARCHAR(255)))
SET @OutputString = STUFF(CAST(@OutputString AS VARCHAR(255)), 5, 0, '-')
PRINT @OutputString

如果能帮助您解决问题,请不要忘记将其标记为答案。 :)