我有一个管道分隔文件,其中包含以下格式的用户和地址信息:
userid|name|street|city|state|zip
123456|fred|123 apple st|Navada|MO|64772
我以以下格式将信息输出到另一个平面文件:
*** DOCUMENT BOUNDARY ***
FORM=LDUSER
.USER_ID. 123456
.USER_ADDR1_BEGIN.
.STREET. 123 apple st
.CITY. Nevada
.STATE. MO
.ZIP. 64772
.USER_ADDR1_END.
是否存在可以进行此类转换的通用SQL或PowerShell脚本?我已经搜索了“将列转换为行”,“将数据透视表转换为平面文件”等短语,但没有发现任何有用的信息。我不确定确切如何调用输出文件的格式,以点/行分隔?分层平面文件?
答案 0 :(得分:1)
据我所知,在SQL Server中没有实现此目的的通用方法,但是如果您设法将数据获取到表中,则以下自定义查询将帮助您将数据呈现为可以导出的单个列之后
CREATE TABLE #temp (UserID INT, Name VARCHAR(40), Street VARCHAR(40), City VARCHAR(40), State VARCHAR(40), Zip INT)
INSERT INTO #temp VALUES
(101,'Kevin Joy','Ap #659-7998 Integer St.','Hinckley','4863 Ligula. Av.',98417),
(102,'Peter Romell','979-4806 Massa Road','Knoxville','4568 A Street',90825),
(103,'Mariam Sid','P.O. Box 547, 8395 Ultrices Av.','Beervelde','Ap #758-6207 Non, Av.',486291),
(104,'Roberta Kotun','9482 Habitant Ave','Northumberland','Ap #620-957 Rutrum Av.',476177)
;WITH CTE AS (
SELECT
CAST(UserID AS VARCHAR(MAX)) AS UserID
,Name
,Street
,City
,[State]
,CAST(Zip AS VARCHAR(MAX)) AS Zip
FROM #temp )
SELECT '*** DOCUMENT BOUNDARY ***' AS [Data]
UNION ALL
SELECT 'FORM=LDUSER'
UNION ALL
SELECT T.Result
FROM CTE
CROSS APPLY (VALUES ('.USER_ID.'+' '+UserID,'Col1'),('.USER_ADDR1_BEGIN.','Col2'),('.STREET.'+' '+Street,'Col3'),('.CITY.'+' '+City,'Col4'),('.STATE.'+' '+[State],'Col5'),('.ZIP.'+' '+Zip,'Col6'),('.USER_ADDR1_END.','Col7')) AS T(Result,Value)
查询结果如下,
*** DOCUMENT BOUNDARY ***
FORM=LDUSER
.USER_ID. 101
.USER_ADDR1_BEGIN.
.STREET. Ap #659-7998 Integer St.
.CITY. Hinckley
.STATE. 4863 Ligula. Av.
.ZIP. 98417
.USER_ADDR1_END.
.USER_ID. 102
.USER_ADDR1_BEGIN.
.STREET. 979-4806 Massa Road
.CITY. Knoxville
.STATE. 4568 A Street
.ZIP. 90825
.USER_ADDR1_END.
.USER_ID. 103
.USER_ADDR1_BEGIN.
.STREET. P.O. Box 547, 8395 Ultrices Av.
.CITY. Beervelde
.STATE. Ap #758-6207 Non, Av.
.ZIP. 486291
.USER_ADDR1_END.
.USER_ID. 104
.USER_ADDR1_BEGIN.
.STREET. 9482 Habitant Ave
.CITY. Northumberland
.STATE. Ap #620-957 Rutrum Av.
.ZIP. 476177
.USER_ADDR1_END.