請參閱 : REPLICATE (Transact-SQL)
B. 使用 REPLICATE 和 DATALENGTH
CREATE TABLE Table1 (
id int
, TableYear NVARCHAR(4)
, TableMonth NVARCHAR(4)
);
INSERT INTO Table1 values
(1, '2022', N'1'),
(2, '2022', N'2'),
(3, '2022', N'3'),
(4, '2022', N'10'),
(5, '2022', N'11');
SELECT id,TableYear+RIGHT('00'+TableMonth,2) AS YYYYMM
FROM Table1
https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=921a4185d280f9f3f11bb6b9cdfb75a8
補充REPLICATE作法
CREATE TABLE Table1 (
id int
, TableYear VARCHAR(4)
, TableMonth VARCHAR(4)
);
INSERT INTO Table1 values
(1, '2022', N'1'),
(2, '2022', N'2'),
(3, '2022', N'3'),
(4, '2022', N'10'),
(5, '2022', N'11');
SELECT id,TableYear+REPLICATE('0',2-DATALENGTH(TableMonth))+TableMonth AS YYYYMM
FROM Table1
https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=89f002b052465592f3202361efc92b53
select * into #A from (values
('1','2022','1')
,('2','2022','2')
,('3','2022','3')
,('4','2022','10')
,('5','2022','11')
) as A([id],[TableYear],[TableMonth]);
select [id], [TableYear]*100+[TableMonth] [YYYYMM]
from #A;