我试图将 txt 文件的内容与表格的每一列的特定位置和长度合并。
Example: From Position: 1 to Position: 7 = Col_1
From Position: 8 to position: 21 = Col_2
From Position: 22 to Position: 47 = Col_3
我CAST(Substring(colum_Name,from_position, to_position) AS data_type) AS colum_name,
用来格式化这个
在合并脚本中,我已经准备好为每一列设置固定的长度和位置。
这就是我想要做的。
创建一个只有一列的表。
CREATE TABLE camposSinFormato(String VARCHAR(255))
GO
然后,BULK 将不带格式的 txt 内容插入该列。
BULK INSERT camposSinFormato
FROM 'F:\genera\completo\STK-TOTAL.TXT'
WITH(
ROWTERMINATOR = '\n'
);
GO
现在,我根据需要使用合并插入或更新表。
我的问题是,为此我必须使用 CAST(SUBSTRING 在更新/插入之前格式化数据,我认为我做错了。
这是我的合并代码示例。
BEGIN TRAN;
MERGE productos AS T
USING camposSinFormato AS S
ON (T.nroTroquel = S.nroTroquel)
WHEN NOT MATCHED BY TARGET
THEN INSERT(
T.nroTroquel,
T.nombre,
T.idlaboratorio,
T.precio,
T.iva,
T.codigobarras,
T.tipoProducto,
T.subtipoProducto,
T.esRefrigerado
)
VALUES
(
CAST(SUBSTRING(S.String, 1, 7)AS BIGINT, PRIMARY KEY) AS nroTroquel,
CAST(SUBSTRING(S.String, 8, 21)AS VARCHAR(50) NOT NULL)AS nombre,
CAST(SUBSTRING(S.String, 22, 47)AS INT NOT NULL) as idlaboratorio,
CAST(SUBSTRING(S.String, 48, 62)AS MONEY NULL) as precio,
CAST(SUBSTRING(S.String, 63, 78)AS INT NULL) as iva,
CAST(SUBSTRING(S.String, 79, 80)AS VARCHAR(13) NULL) as codigobarras,
CAST(SUBSTRING(S.String, 81, 82)AS VARCHAR(14) NULL) as tipoProducto,
CAST(SUBSTRING(S.String, 83, 84)AS VARCHAR(15) NULL) as subTipoProducto,
CAST(SUBSTRING(S.String, 85, 91)AS BIT NULL) as esRefrigerado
)
WHEN MATCHED
THEN UPDATE
SET T.nombre = CAST(SUBSTRING(String, 8, 21)AS VARCHAR(50) NOT NULL)AS nombre,
T.idlaboratorio = CAST(SUBSTRING(String, 22, 47)AS INT NOT NULL) as idlaboratorio,
T.iva = CAST(SUBSTRING(String, 63, 78)AS INT NULL) as iva,
T.codigobarras = CAST(SUBSTRING(String, 79, 80)AS VARCHAR(13) NULL) as codigobarras,
T.tipoProducto = CAST(SUBSTRING(String, 81, 82)AS VARCHAR(14) NULL) as tipoProducto,
T.subtipoProducto = CAST(SUBSTRING(String, 83, 84)AS VARCHAR(15) NULL) as subTipoProducto,
T.esRefrigerado = CAST(SUBSTRING(String, 85, 91)AS BIT NULL) as esRefrigerado
WHERE S.nroTroquel = T.nroTroquel
OUTPUT $action, updated, inserted.*;
任何人都可以告诉我我这样做的方式是否正确?
提前致谢。
PS:抱歉编辑,我在原文章中解释错了