我寫了一個查詢來創建一個字符串並在值之間添加填充。然後將其作爲文本文件導出,以便加載到遺留系統中。SQL Server添加填充到字符串
我已經使用表變量從table1中提取所有源數據,然後使用CAST運行查詢以使用填充創建所需的字符串。
我的問題是;如果不使用表變量(或臨時表),可以使用更少的步驟來實現這一點,而CAST是最好的方法嗎?
不幸的是,使用填充字符串是創建合適的上傳文件的唯一方法。
樣本數據和查詢:
CREATE TABLE dbo.table1(
[source1] [varchar](6),
[source2] [varchar](8),
[source3] [varchar](6),
[source4] [varchar](3),
[source5] [varchar](10),
[source6] [varchar](5),
[source7] [decimal](17, 2)
);
INSERT INTO dbo.table1 VALUES (999999,55566889,8964,'OPL',25648,'CR',12.35);
INSERT INTO dbo.table1 VALUES (222222,44422258,2548,'EWP',25698,'CR',10248.25);
INSERT INTO dbo.table1 VALUES (999999,33355589,3655,'SDO',75869,'DR',-897623.25);
INSERT INTO dbo.table1 VALUES (444444,11155987,5742,'SVI',25698,'CR',100023.36);
INSERT INTO dbo.table1 VALUES (555555,41555585,2586,'PLW',65879,'DR',-45.69);
Declare @TempTableVariable Table(
column1 nchar(15),
column2 nchar(6),
column3 nchar(3),
column4 nchar(10),
column5 nchar(6),
column6 nchar(25),
column7 nchar(17),
column8 nchar(17)
);
INSERT INTO @TempTableVariable
SELECT
source1 + source2 AS column1,
source3 AS column2,
source4 AS column3,
source5 AS column4,
source1 AS column5,
source6 AS column6,
CASE WHEN source7 > 0 THEN ABS(source7) ELSE NULL END AS column7,
CASE WHEN source7 < 0 THEN ABS(source7) ELSE NULL END AS column8
FROM dbo.table1
WHERE source1 = '999999';
SELECT
column1 AS SetID,
CAST(ISNULL(column2,'') AS nchar(4)) +
CAST(ISNULL(column3,'') AS nchar(6)) +
CAST(ISNULL(column4,'') AS nchar(14)) +
CAST(column5 AS nchar(7)) +
CAST(column1 AS nchar(15)) +
CAST(ISNULL(column7,'') AS nchar(17)) +
CAST(ISNULL(column8,'') AS nchar(17)) AS Input
FROM @TempTableVariable;
結果:
SETID|INPUT
99999955566889|8964OPL 25648 999999 99999955566889 12.35
99999933355589|3655SDO 75869 999999 99999933355589 897623.25
謝謝。
您可以將INSERT語句封裝在CTE中,然後擺脫@TempTableVariable,請參閱下面的答案。 – NickyvV