以pipe del格式返回数据

时间:2016-06-21 12:38:21

标签: sql-server

我有以下示例,并尝试在SQL中运行脚本以返回所需格式的数据。只需要一些帮助“标题”,“数据”和“预告片”部分。

H|Peter|Blum|2012/07/30|1
D|11399011005434578|Jason|Smith|8002235091083|0126531988|199 Lever Road Centurion Gauteng 0067|23.45|Your next payment is due on 2012/09/02|2012/07/29|Active
D|11399022005434578|Mike|Smith|8004235091083|0126531988|299 Lever Road Centurion Gauteng 0067|55.00|Your next payment is due on 2012/09/03|2012/06/29|Active
D|11399033005434578|Peter|Smith|8052235091083|0126531988|399 Lever Road Centurion Gauteng 0067|77.99|Your next payment is due on 2012/09/04|2012/05/29|Active
T|3

2 个答案:

答案 0 :(得分:0)

从您提供的示例中我收集到您正在尝试创建文件。 您需要使用bcp实用程序来创建文件。

您接近它的方式如下:

CREATE TABLE ##FileData( ID INT IDENTITY, RowString VARCHAR( MAX ))
INSERT INTO ##FileData
SELECT 'H|Peter|Blum|2012/07/30|1'

INSERT INTO ##FileData
SELECT 'D|' + CONVERT( VARCHAR, Col1 ) + '|' + CONVERT( VARCHAR, Col2 ) + '|' + ....
FROM MyTable

/* Get record count */
DECLARE @RowCount = ( SELECT COUNT(*) FROM #FileData ) - 1

INSERT INTO ##FileData
SELECT 'T|' + CONVERT( VARCHAR, @RowCount )

EXEC master..xp_cmdshell
N'bcp "SELECT RowString FROM ##FileData" queryout  C:\MyFile.txt  -c -r\r\n -S[ServerName] -U[username] -P[password] '

答案 1 :(得分:0)

您可以使用UNION ALL添加标题和预告片:

SELECT {Query that generates Header}, 0 AS ord
UNION ALL 
SELECT {Query that generates Data Rows}, 1 AS ord
UNION ALL
SELECT {Query that generates Trailer}, 2 AS ord
ORDER BY ord ASC