Solved

Row sort order on SQL script to export query to CSV via BCP

Posted on 2012-04-10
3
830 Views
Last Modified: 2012-04-30
I'm having trouble with the query I wrote below.This script runs on SQL Server 2005 Express edition (meaning no DTS / SSIS) This script is used to add a header row to the export with column names (something BCP can't do natively)

The problem with this script is that the header row created on lines 156 - 175 does not always return at the top despite the sort by the temp column.

How can I fix the sort order in this script? Would i be better off adding an identity column?

if object_id('##TempExportData') is not null
    drop table ##TempExportData
if object_id('##TempExportData2') is not null
    drop table ##TempExportData2

declare @columnNames varchar(max), @columnConvert varchar(max), @tempSQL varchar(max), @xpCMDText varchar(8000)

-- insert data into a global temp table

SELECT 					a._1402 AS contacts_birthdate,
						c._1240 AS contacts_email .....[code truncated for readability]...........

		into ##TempExportData
		FROM myTable AS a .....[code truncated for readability].............

-- build 2 lists
-- 1. column names
-- 2. columns converted to nvarchar
SELECT   @columnNames = COALESCE( @columnNames  + ',', '') + column_name,
        @columnConvert = COALESCE( @columnConvert  + ',', '') + 'convert(nvarchar(4000),' 
        +	case when data_type = 'varchar' then  'QuoteName('+column_name+',''"'')' 
			else column_name 
			end

			+ case when data_type in ('datetime', 'smalldatetime') then ',121'
                             when data_type in ('numeric', 'decimal') then ',128'
                             when data_type in ('float', 'real', 'money', 'smallmoney') then ',2'
                             when data_type in ('datetime', 'smalldatetime') then ',120'
                             else ''
                        end + ')as ' + column_name
FROM    tempdb.INFORMATION_SCHEMA.Columns
WHERE    table_name = '##TempExportData'

-- execute select query to insert data and column names into new temp table
SELECT    @sql = 'select ' + @columnNames + ' into ##TempExportData2 from (select ' + @columnConvert + ', ''2'' as [temp##SortID] 
       from ##TempExportData union all select ''' + replace(@columnNames, ',', ''', ''') + ''', ''1'') t order by [temp##SortID]'
print (@sql)
exec (@sql)

-- build full BCP query

--- Change the following 
---  -U[sql username here] -P[sql pw here]  or use -T to use a trusted account


select @xpCMDText = 'bcp " select * from ##TempExportData2 " queryout "' + @fullFileName + '" -c -Slocalhost\EMMSDE -t","  -T -CRAW'

-- execute BCP
Exec master..xp_cmdshell @xpCMDText

Open in new window

0
Comment
Question by:Intuvo
3 Comments
 
LVL 39

Accepted Solution

by:
appari earned 500 total points
ID: 37830879
try changing like this

-- execute select query to insert data and column names into new temp table
SELECT    @sql = 'select * into ##TempExportData2 from (select ' + @columnConvert + ', ''2'' as [temp##SortID]
       from ##TempExportData union all select ''' + replace(@columnNames, ',', ''', ''') + ''', ''1'') t order by [temp##SortID]'
print (@sql)
exec (@sql)

-- build full BCP query

--- Change the following
---  -U[sql username here] -P[sql pw here]  or use -T to use a trusted account


select @xpCMDText = 'bcp " select  ' + @columnNames + ' from ##TempExportData2 order by [temp##SortID] " queryout "' + @fullFileName + '" -c -Slocalhost\EMMSDE -t","  -T -CRAW'

-- execute BCP
Exec master..xp_cmdshell @xpCMDText
0
 
LVL 10

Expert Comment

by:sqlservr
ID: 37831299
for More info on BCP command , have a look into my blog

http://sqlservr.blog.com/
0
 

Author Closing Comment

by:Intuvo
ID: 37912232
The temp sort order did the trick! Thanks!
0

Featured Post

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

Occasionally there is a need to clean table columns, especially if you have inherited legacy data. There are obviously many ways to accomplish that, including elaborate UPDATE queries with anywhere from one to numerous REPLACE functions (even within…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Familiarize people with the process of utilizing SQL Server functions from within Microsoft Access. Microsoft Access is a very powerful client/server development tool. One of the SQL Server objects that you can interact with from within Microsoft Ac…
Via a live example, show how to setup several different housekeeping processes for a SQL Server.

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now