我有varchar列,它的名字是column1,有像111232435-0和1123443530这样的记录。最后一个数字并不总是0;它可以是0-9。
其中一些是带(-)的数字,另一些是数字。我想将数字改为(-)的数字。
例如:1123443530 ->改为-> 112344353-0
伪码:
if record just be digit just update in column3
else
the last digit separate by (-)
and then record update in column3在Server 2012中,并将此新记录和记录(-)放在新列中。
我该怎么办?
发布于 2018-08-21 08:11:13
另一种选择是使用料子函数。
IF OBJECT_ID('tempdb..#ExampleValues') IS NOT NULL
DROP TABLE #ExampleValues
CREATE TABLE #ExampleValues (
ExampleValue VARCHAR(100),
UpdatedValue VARCHAR(100))
INSERT INTO #ExampleValues (ExampleValue)
VALUES
('112344353-0'),
('11443-8'),
('112344-9'),
('11234435348'),
('11234448712')
UPDATE T SET
UpdatedValue = CASE
WHEN T.ExampleValue NOT LIKE '%-%' -- If the literal does not contain a hyphen
THEN STUFF(
T.ExampleValue, -- Put in the literal
LEN(T.ExampleValue), -- Just before the last character
0, -- While replacing 0 characters ("stuffing" in between)
'-') -- Place a hypen!
ELSE
T.ExampleValue END
FROM
#ExampleValues AS T
SELECT
T.ExampleValue,
T.UpdatedValue
FROM
#ExampleValues AS T结果:
ExampleValue UpdatedValue
112344353-0 112344353-0
11443-8 11443-8
112344-9 112344-9
11234435348 1123443534-8
11234448712 1123444871-2发布于 2018-08-21 05:00:49
这是你要找的东西吗?
DECLARE @table TABLE(varname VARCHAR(255),
newvarname VARCHAR(255)
);
INSERT INTO @table
SELECT '111232435-0',NULL
UNION ALL
SELECT '1123443530',NULL;
UPDATE @table
SET
newvarname = CASE
WHEN varname NOT LIKE '%-%' THEN
LEFT(varname,LEN(varname)-1)+'-'+RIGHT(varname,1)
ELSE varname
END;
SELECT *
FROM @table;根据上述逻辑,您可以创建update语句。
如果最后一个数字可以是任意数字,则编辑1更新代码,并假设我们只需要更改没有分隔器-的列
https://dba.stackexchange.com/questions/215440
复制相似问题