我在'-'上分割了'0021C-15563017-2',
我想在T2(clntcode,certno.depcode)中插入(0021c
,15563017
,2
),参见图片。
我尝试使用交叉申请将拆分值插入到表的行中(img 2),但不起作用。
我使用过的查询:
SELECT CLNTCODE, certno, depcode
FROM T2
CROSS APPLY STRING_SPLIT('0021C-15563017-2', '-');
答案 0 :(得分:2)
我建议不要在这里使用STRING_SPLIT
,因为可能很难从连字符分隔的字符串中找出这三个组成部分。相反,我建议使用CHARINDEX
:
WITH T2 AS (
SELECT '0021C-15563017-2' AS col
)
SELECT
LEFT(col, CHARINDEX('-', col) - 1) AS CLNTCODE,
SUBSTRING(col,
CHARINDEX('-', col) + 1,
CHARINDEX('-', col, CHARINDEX('-', col) + 1) -
CHARINDEX('-', col) - 1) AS certno,
SUBSTRING(col, CHARINDEX('-', col, CHARINDEX('-', col) + 1) + 1, LEN(col))
AS depcode
FROM T2;
请注意,STRING_SPLIT
在这里很难使用,因为很难从该函数的表值响应中寻址给定记录。
答案 1 :(得分:0)
insert into t2 (CLNTCODE, certno, depcode )
select *
from
(
select *,row_number() over (order by value ) as rn from STRING_SPLIT('0021C-15563017-2', '-')
) src
pivot
(
max(value)
for rn in ([1], [2], [3])
) piv;
答案 2 :(得分:0)
您在这里:
CREATE TABLE YourTable(
CLNTCODE VARCHAR(25),
certno VARCHAR(25),
depcode VARCHAR(25)
);
WITH StrTbl(Col1, Col3, Str) AS
(
SELECT LEFT(Str, CHARINDEX('-', Str) - 1) Col1,
LEFT(REVERSE(Str), CHARINDEX('-', REVERSE(Str)) - 1) Col3,
Str
FROM
(
SELECT '0021C-15563017-2' AS Str
UNION
SELECT '0021C-1-2'
) T
)
INSERT INTO YourTable (CLNTCODE, certno, depcode)
SELECT Col1,
REPLACE(REPLACE(REPLACE(Str, Col1, ''), Col3, ''), '-', '') AS Col2,
Col3
FROM StrTbl;
SELECT *
FROM YourTable;
结果:
+----+----------+----------+---------+
| | CLNTCODE | certno | depcode |
+----+----------+----------+---------+
| 1 | 0021C | 15563017 | 2 |
| 2 | 0021C | 1 | 2 |
+----+----------+----------+---------+
答案 3 :(得分:0)
如果适合某人,也可以使用以下方法。
INSERT INTO T2 (CLNTCODE, certno, depcode)
SELECT LEFT('0021C-15563017-2', CHARINDEX('-', '0021C-15563017-2') - 1) AS CLNTCODE,
LEFT(REPLACE('0021C-15563017-2', LEFT('0021C-15563017-2', CHARINDEX('-', '0021C-15563017-2')), ''), CHARINDEX('-', REPLACE('0021C-15563017-2', LEFT('0021C-15563017-2', CHARINDEX('-', '0021C-15563017-2')), '')) - 1) AS certno,
LEFT(REVERSE('0021C-15563017-2'), CHARINDEX('-', REVERSE('0021C-15563017-2')) - 1) AS depcode