From SQL Server 2005, I n开发者_C百科eed to do an export for a client to an xml-like format shown below. Why they are not using XML, I don't know. Any ideas on how to do this quickly without exporting the file "FOR XML" and then writing a messy script to go through the text file and find and replace <, >, and every closing XML tag? Thank you.
START_FILE:
DATE:
COLUMN1:A
COLUMN2:B
COLUMN3:C
COLUMN1:D
COLUMN2:E
COLUMN3:F
COLUMN1:G
COLUMN2:H
COLUMN3:I
END_FILE:
DECLARE @Output nvarchar(max)
SET @Output = 'START_FILE:
DATE:'
SELECT @Output = @Output + '
COLUMN1:' + Col1 + '
COLUMN2:' + Col2 + '
COLUMN3:' + Col3
FROM YourTable
ORDER BY Col1
SELECT @Output + '
END_FILE:' AS Result
I went with Martin's suggestion of trying an UNPIVOT query, which was all new to me. Using SSIS, I am now exporting the query to a text file formatted exactly as I need it with a run time of just a few seconds. I am using a query like below with a ":" as a column delimiter. Great suggestion Martin!
SELECT 'START_FILE' as FieldName, '' as 'FieldValue'
UNION ALL
select 'DATE' as FieldName, getDate() as 'FieldValue'
UNION ALL
SELECT FieldName, FieldValue
FROM
(
SELECT
Cast(Column1Name as varchar) as VendorColumn1Name,
Cast(Column2Name as varchar) as VendorColumn2Name,
Cast(Column3Name as varchar) as VendorColumn3Name
FROM MyTable
) c
UNPIVOT
(
FieldValue for FieldName IN(VendorColumn1Name, VendorColumn2Name, VendorColumn3Name)
) as p
UNION ALL
SELECT 'END_FILE' as FieldName, '' as 'FieldValue'
精彩评论