Try this stored procedure
USE master
GO
IF object_id('spExportData') IS NOT NULL
DROP PROCEDURE spExportData
GO
CREATE PROCEDURE spExportData (
@dbName VARCHAR(100) = 'master'
,@sql VARCHAR(5000) = ''
,@fullFileName VARCHAR(100) = ''
)
AS
IF @sql = '' OR @fullFileName = ''
BEGIN
SELECT 0 AS ReturnValue -- failure
RETURN
END
-- if DB isn't passed in set it to master
SELECT @dbName = 'use ' + @dbName + ';'
IF object_id('##TempExportData') IS NOT NULL
DROP TABLE ##TempExportData
IF object_id('##TempExportData2') IS NOT NULL
DROP TABLE ##TempExportData2
-- insert data into a global temp table
DECLARE @columnNames VARCHAR(8000)
,@columnConvert VARCHAR(8000)
,@tempSQL VARCHAR(8000)
SELECT @tempSQL = left(@sql, charindex('from', @sql) - 1) + ' into ##TempExportData ' + substring(@sql, charindex('from', @sql) - 1, len(@sql))
EXEC (@dbName + @tempSQL)
IF @@error > 0
BEGIN
SELECT 0 AS ReturnValue -- failure
RETURN
END
-- build 2 lists
-- 1. column names
-- 2. columns converted to nvarchar
SELECT @columnNames = COALESCE(@columnNames + ',', '') + column_name
,@columnConvert = COALESCE(@columnConvert + ',', '') + 'convert(nvarchar(4000),' + column_name + 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]'
EXEC (@sql)
-- build full BCP query
SELECT @sql = 'bcp "' + @dbName + ' select * from ##TempExportData2" queryout "' + @fullFileName + '" -c -CRAW'
-- execute BCP
EXEC master..xp_cmdshell @sql
IF @@error > 0
BEGIN
SELECT 0 AS ReturnValue -- failure
RETURN
END
DROP TABLE ##TempExportData
DROP TABLE ##TempExportData2
SELECT 1 AS ReturnValue -- success
Here you execute the query you want.
For example:
DECLARE @sql VARCHAR(6800)
,@dbName VARCHAR(100)
,@fullFileName VARCHAR(100)
SELECT @dbName = 'northwind'
,@sql = 'select * from orders order by orderdate'
,@fullFileName = 'e:\test.xls'
EXEC master..spExportData @dbName
,@sql
,@fullFileName
I've got the query from here a couple years ago, and it's pretty neat.