Solved

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

Posted on 2012-04-10
3
908 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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:Ramesh Babu Vavilla
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

On Demand Webinar - Networking for the Cloud Era

This webinar discusses:
-Common barriers companies experience when moving to the cloud
-How SD-WAN changes the way we look at networks
-Best practices customers should employ moving forward with cloud migration
-What happens behind the scenes of SteelConnect’s one-click button

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Why is this different from all of the other step by step guides?  Because I make a living as a DBA and not as a writer and I lived through this experience. Defining the name: When I talk to people they say different names on this subject stuff l…
Load balancing is the method of dividing the total amount of work performed by one computer between two or more computers. Its aim is to get more work done in the same amount of time, ensuring that all the users get served faster.
This video shows how to set up a shell script to accept a positional parameter when called, pass that to a SQL script, accept the output from the statement back and then manipulate it in the Shell.
Viewers will learn how the fundamental information of how to create a table.

688 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