我想在此示例中创建感兴趣的删除仪表板(3-,2-)的功能:
柱:
1GBDDR3-1066-21
2GBDDR3-1066-21
3- 4GBDDR3-1066-414
1GBDDR3-1066-21
2-1GBDDR3-1066-21
输出:
1GBDDR3-1066-21
2GBDDR3-1066-21
4GBDDR3-1066-414
1GBDDR3-1066-21
1GBDDR3-1066-21
答案 0 :(得分:8)
您可以将PATINDEX
与RIGHT
,LEN
和LTRIM
一起使用:
创建并填充样本表(请保存是您未来问题中的此步骤)
DECLARE @T AS TABLE
(
col varchar(30)
)
INSERT INTO @T VALUES
('1GBDDR3-1066-21'),
('2GBDDR3-1066-21'),
('3- 4GBDDR3-1066-414'),
('1GBDDR3-1066-21'),
('2-1GBDDR3-1066-21')
查询:
SELECT CASE WHEN PATINDEX('[0-9]-%', col) > 0 THEN
LTRIM(RIGHT(col, LEN(col)-2))
ELSE
col
END
FROM @T
结果:
1GBDDR3-1066-21
2GBDDR3-1066-21
4GBDDR3-1066-414
1GBDDR3-1066-21
1GBDDR3-1066-21
答案 1 :(得分:4)
我会使用stuff()
:
select (case when col like '_-%' then stuff(col, 2, 1, '') else col
end)
注意:问题是关于破折号的,所以我假设第三行的空格是拼写错误。
答案 2 :(得分:2)
替代解决方案;
DECLARE @T AS TABLE
(
col varchar(30)
)
INSERT INTO @T VALUES
('1GBDDR3-1066-21'),
('2GBDDR3-1066-21'),
('3- 4GBDDR3-1066-414'),
('1GBDDR3-1066-21'),
('2-1GBDDR3-1066-21')
DECLARE @refValue NVARCHAR(7)='GBDDR3'
SELECT
RIGHT((LEFT(col, CHARINDEX(@refValue,col)-1)),1)
+@refValue
+RIGHT(col,LEN(col)-(CHARINDEX(@refValue,col) + LEN(@refValue))+1) FROM @T
答案 3 :(得分:1)
如果该表中只有GBDDR
,那么您可以使用:
SELECT SUBSTRING(columnName,CHARINDEX('GB',columnName)-1,LEN(columnName))
FROM tableName
或者:
SELECT CASE WHEN LEN(columnName)-LEN(REPLACE(columnName,'-','')) > 2
--if we got more than two dashes
THEN LTRIM(SUBSTRING(columnName,CHARINDEX('-',columnName)+1,LEN(columnName)))
--take sub-string from first occurrence of dash+1 to the end of the string
ELSE columnName END
--else take the full string
FROM tableName
输出:
1GBDDR3-1066-21
2GBDDR3-1066-21
4GBDDR3-1066-414
1GBDDR3-1066-21
1GBDDR3-1066-21