Link to home
Start Free TrialLog in
Avatar of Neil Thompson
Neil ThompsonFlag for United Kingdom of Great Britain and Northern Ireland

asked on

How best to create a specific file with header and footer incorporating modified select data

Hi

I've got to produce on a daily basis an export file to upload to a payment provider. I'm pulling my data back initially using the following SQL which lists the uprn and price Any ideas for the best way forward? Its well beyond my SQL knowledge but I guess if there is no luck here I could try it all in PHP.

SELECT  b.c_uprn,
        g.green_uprn
	CASE 
		WHEN g.green_uprn IS NOT NULL THEN 10.00
		ELSE 20.00
	END price
FROM    t_blpu b
        LEFT OUTER JOIN t_refuse_garden_2014 g ON b.c_uprn = '0000' + g.green_uprn
ORDER BY 
	g.green_uprn DESC 

Open in new window


Which gives me a file approximately 64372 lines long containing data like this (uprn/price in pence):
40121018	3895
40118160	3895
40117792	3895
40117638	3895
40117634	3895
40117633	3895
40117629	3895

Open in new window


Now, I need to wrap this with a header and footer. The header is quite easy as its preset with just the date (in bold) changing:
H,242,[b]20140727 16:07:00[/b],F,14,7.0

Open in new window


The footer however is trickier as its preset in part but requires the date again then the total number of records, then the amount of all the prices totalled up
T,242,[b]20140727 16:07:00[/b],[b]64372[/b],[b]395828570[/b],0

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Jim Horn
Jim Horn
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I wouldn't try to do the data concatenation in SQL Server.  That will lead to maintenance headaches.

Use SQL's bcp utility to separately create the three files, then use a standard DOS/Windows command file to concatenate the files.

Bcp is a command-line utility and is a pain to get working the first time.  But once you've got it going, it's not that bad.  Here's sample code to use bcp to create the header file.

DECLARE @bcp_command varchar(8000)
DECLARE @header_file varchar(500)
DECLARE @body_file varchar(500)
DECLARE @footer_file varchar(500)

SET @header_file = 'C:\header.txt'

SET @bcp_command = 'bcp "SELECT ''H,242,' +
    CONVERT(varchar(8), GETDATE(), 112) + ' ' + CONVERT(varchar(8), GETDATE(), 8) +
    ',F,14,7.0''" queryout "' + @header_file + '" -r\r\n -S server\instance -t, -T -w'
PRINT @bcp_command

EXEC xp_cmdshell @bcp_command
EXEC xp_cmdshell 'type "c:\header.txt"'
EXEC xp_cmdshell 'del "c:\header.txt"'

[Btw, if you do use SQL to concatenate the data, you'd want to use UNION ALL not UNION.]
Avatar of Neil Thompson

ASKER

Apologies for the delay. Been away on holiday for the last 6 weeks

Great answer, helped instantly

Regards